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.

不许用加减法,那就基本是位操作了。
两个整数在二进制下,相与可以得到该位是否有进位的信息,异或可以得到排除进位以后的相加结果。
那么先将两个数相与,得到进位信息,并将进位信息左移一位待用;
将两个数做异或,得到无进位的结果;
如果刚才的进位是0,则完结;
如果不是,再将这个结果与刚才的进位作为新的加数。

var getSum = function(a, b) {
    while (b!==0) {
        var c = a&b;
        a = a^b;
        b = c<<1;
    }
    return a;
};

你可能感兴趣的:(371. Sum of Two Integers)