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.

Solution:

当a和b相加的每一位都没有carry的时候(ab:01/10/00),a+b的和就等于 a^b,

把b当成一个carry开始,求它与a的和,就是要求不算carry的值(a^b),再加上更新后的carry(a&b << 1)

public int getSum(int a, int b) {
        while(b!=0){
            int carry = (a&b)<<1;
            a = a^b;
            b = carry;
        }  
        return a;
    }

results matching ""

    No results matching ""