LeetCode/371. Sum of Two Integers.md
2018-10-26 23:40:21 +08:00

1.0 KiB
Raw Blame History

371. Sum of Two Integers

思路

求两个数的和,要求不能使用操作符+、-。
我们知道计算机底层中的四则运算都是用门电路通过简单的逻辑操作实现的, 例如对于一位的二进制加法:

a b sum(和) cin(进位)
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1

所以一位加法规则是: sum = a ^ b, cin = a & b.
对于多位的加法我们可以先分别求出sum和cin, 再用sum和左移一位的cin相加求出新的sum和cin, 循环直到cin为0.

C++

class Solution {
public:
    int getSum(int a, int b) {
        int res = a ^ b, cin = a & b; // 异或操作'^': 相同为0不同为1
        while(cin != 0){
            a = cin << 1;
            b = res;
            res = a ^ b;
            cin = a & b;
        }
        return res;
    }
};