您的位置:首页 > 其它

<LeetCode OJ> 371. Sum of Two Integers

2016-07-02 18:25 453 查看
Total Accepted: 3722 Total
Submissions: 6898 Difficulty: Easy

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

Hide Tags
Bit Manipulation

Hide Similar Problems
(M) Add Two Numbers

分析:

说实话每次看到位运算我就头疼。其实不会此问题,纯属学习!虽然知道用位运算,知道与或非的原理!

来自分析区

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题解索引:/article/3664871.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: