Skip to content

Commit 16d2846

Browse files
committed
371
1 parent 51337c4 commit 16d2846

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

ruby/371-Sum-of-Two-Integers.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def get_sum(a, b)
2+
mask = 0xffffffff
3+
until b.zero? # until no carries left
4+
tmp = (a & b) << 1 # carries
5+
a = (a ^ b) & mask # addition w/o carries
6+
b = tmp & mask
7+
end
8+
a = ~(a ^ mask) if a > (mask >> 1)
9+
a
10+
end
11+
12+
# Ugly Solution
13+
def get_sum(a, b)
14+
mask = 0xffffffff # 32 bit maximum
15+
res = 0
16+
carry = 0
17+
32.times do |n|
18+
bit_a = (a >> n) & 1
19+
bit_b = (b >> n) & 1
20+
21+
if (bit_a | bit_b).zero?
22+
if carry == 1
23+
carry -= 1
24+
res |= (1 << n)
25+
end
26+
elsif (bit_a & bit_b) == 1
27+
if carry == 1
28+
res |= (1 << n)
29+
else
30+
carry += 1
31+
end
32+
elsif carry.zero?
33+
res |= (1 << n)
34+
end
35+
end
36+
res &= mask
37+
if (res >> 31) & 1 == 1
38+
# XOR flips rightmost 32, then NOT flips all bits
39+
res = ~(res ^ mask)
40+
end
41+
res
42+
end

0 commit comments

Comments
 (0)