forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
51337c4
commit 16d2846
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
def get_sum(a, b) | ||
mask = 0xffffffff | ||
until b.zero? # until no carries left | ||
tmp = (a & b) << 1 # carries | ||
a = (a ^ b) & mask # addition w/o carries | ||
b = tmp & mask | ||
end | ||
a = ~(a ^ mask) if a > (mask >> 1) | ||
a | ||
end | ||
|
||
# Ugly Solution | ||
def get_sum(a, b) | ||
mask = 0xffffffff # 32 bit maximum | ||
res = 0 | ||
carry = 0 | ||
32.times do |n| | ||
bit_a = (a >> n) & 1 | ||
bit_b = (b >> n) & 1 | ||
|
||
if (bit_a | bit_b).zero? | ||
if carry == 1 | ||
carry -= 1 | ||
res |= (1 << n) | ||
end | ||
elsif (bit_a & bit_b) == 1 | ||
if carry == 1 | ||
res |= (1 << n) | ||
else | ||
carry += 1 | ||
end | ||
elsif carry.zero? | ||
res |= (1 << n) | ||
end | ||
end | ||
res &= mask | ||
if (res >> 31) & 1 == 1 | ||
# XOR flips rightmost 32, then NOT flips all bits | ||
res = ~(res ^ mask) | ||
end | ||
res | ||
end |