Sum of Two Integers
Given two integers a
and b
, return the sum of the two integers without using the operators +
and -
.
My Solutions:
a ^ b: 代表a和b相加后,应该进位的地方不进位的结果
a
b
a XORb
0
0
0
0
1
1
1
0
1
1
1
0
a & b: 代表a和b都是1的结果; a & b << 1: 代表进位之后的结果
比如a=1(000...001), b=3(000...011)
a^b=000...010, (a&b)<<1= 000...001<<1 = 000...010 --> a=010, b=010
a^b=000, (a&b)<<1=010<<1=0100 --> a=000, b=0100
a^b=0100, (a&b)<<1=0000 --> a=0100, b=0000, stop here
public int getSum(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
Last updated