Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
Solution
Think this problem with an example.
Consider 15+9=24.
1
2
3
4
5
00001111
XOR 00001001
-------------
00000110
1
2
3
4
5
#AND holds the carry part of the result
00001111
AND 00001001
-------------
00001001
1
2
3
4
5
# shift the carry to left for 1 place, and add with the remaining
00000110
+ 00010010
-------------
00011000
Thus, for any integer a and b, a + b = a^b + (a&b)<<1. Because + operator is not allowed, we can regard a^b as new a, and (a&b)<<1 as new b. Repeat this until current carry is 0.
近期评论