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.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析:
说实话每次看到位运算我就头疼。其实不会此问题,纯属学习!虽然知道用位运算,知道与或非的原理!
来自分析区
I have been confused about bit manipulation for a very long time. So I decide to do a summary about it here.
"&" AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)
"^" XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)
"~" NOT operation, for example, ~2(0010) => -3 (1101) what??? Don't get frustrated here. It's called two's complement.
1111 is -1, in two's complement
1110 is -2, which is ~2 + 1, ~0010 => 1101, 1101 + 1 = 1110 => 2
1101 is -3, which is ~3 + 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 "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)
class Solution { public: int getSum(int a, int b) { if (a == 0) return b; if (b == 0) return a; int carry=0,add=0; while (b != 0) { add = a ^ b; //模拟加运算 carry = (a & b) << 1; //获取进位 a=add; b=carry; } return a; } };
可以很容易地用“异或”和“或”操作实现整数加法运算:对应位数的“异或操作”可得到该位的数值,对应位的“与操作”可得到该位产生的高位进位,如:a=010010,b=100111,计算步骤如下:
第一轮:a^b=110101,(a&b)<<1=000100, 由于进位(000100)大于0,
则进入下一轮计算,a=110101,b=000100,a^b=110001,(a&b)<<1=001000,
由于进位大于0,则进入下一轮计算:a=110001,b=001000,a^b=111001,(a&b)<<1=0,
进位为0,终止,计算结果为:111001。
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51812032
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895