leetcode 371. Sum of Two Integers

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.
不用加减法进行求和运算。

^来实现二进制的加法,同时用移位来进行进位。 可以用while循环来进行模拟操作,当不用进位的时候,跳出即可。

class Solution {
public:
    int getSum(int a, int b) {
        while (b) {
            int c = a ^ b;
            b = (a & b) << 1;
            a = c;
        }
        return a;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/8485270.html