Calculate the sum of of the integers a and b, but is not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
I have the been confused about bit manipulation for a very long time. So I decide to does a summary about it here.
"&" and operation, for example, 2 (0010) & 7 (0111) = 2 (0010)
"^" XOR operation, for example, 2 (0010) ^ 7 (0111) and 5 (0101)
"~" Not operation, for example, (0010) = 3 (1101) What??? Don ' t get frustrated here. It's called and complement.
1111 is-1, in both ' s complement
1110 Is-2, which is 1, ~0010 = 1101, 1101 + 1 = 1110 + 2
1101 Is-3, which is ~ + 1
So if you want to get a negative number, you can simply do ~x + 1
Reference:
Https://en.wikipedia.org/wiki/Two%27s_complement
Https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
For this, problem, for example, we have a = 1, b = 3,
In bit representation, a = 0001, B = 0011,
First, we can use the "and" ("&") operation between A and B to find a carry.
carry = A & B, then carry = 0001
Second, we can use "xor" ("^") operation between A and B to find the different bit, and assign it to a,
Then, we shift carry one position left and assign it to B, B = 0010.
Iterate until there is no carry (or b = = 0)
//iterative Public intGetsum (intAintb) {if(A = = 0)returnb; if(b = = 0)returnA; while(b! = 0) { intCarry = A &b; A= a ^b; b= Carry << 1; } returnA;}//iterative Public intGetsubtract (intAintb) { while(b! = 0) { intBorrow = (~a) &b; A= a ^b; b= Borrow << 1; } returnA;}//Recursive Public intGetsum (intAintb) {return(b = = 0)? A:getsum (a ^ B, (A & B) << 1);}//Recursive Public intGetsubtract (intAintb) {return(b = = 0)? A:getsubtract (a ^ B, (~a & B) << 1);}//Get Negative number Public intNegateintx) {return~x + 1;}
Very good explanation:
http://www.geeksforgeeks.org/subtract-two-numbers-without-using-arithmetic-operators/
Reference:https://discuss.leetcode.com/topic/49771/java-simple-easy-understand-solution-with-explanation
Sum of integers