371 sum of two integers

(a&b)<<1 计算出所有的进位
a^b 计算出相加和

然后用a保存相加和,b保存进位,循环用和进位,直到进位为零

int getSum(int a, int b) {
    int carry = 0;

    while(b){
        carry = (a&b)<<1;
        a = a^b;
        b = carry;
    }

    
    return a;
}

你可能感兴趣的:(371 sum of two integers)