371. Sum of Two Integers

需要知道以下几点:
XOR 返还不一样,不一样的相加那么结果是1。
AND 返还进位,进位之后肯定是0.

相当于原题变为A+B之后,算2部分,第一部分是相加之后没进位的那些bits,都是1,第二部分是进位的那些bits.
两部分相加就行了。
用迭代,停止的情况是第二部分是0。。

public int getSum(int a, int b) {
        if( b == 0 ) return a;
        
        int plus = a ^ b;
        int more = a & b;
        more = more << 1;
        
        return getSum(plus,more);
    }

plus是没进位的那些
more是进位的那些,因为进位了所以要左移1
比如 0101+0101
more = 0101 实际应该是1010 (more<<1)

原文地址:https://www.cnblogs.com/reboot329/p/5875882.html