Tuesday, December 27, 2016

371. Sum of Two Integers

Q:

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.

A:

就是按位亦或,再把进位右移,继续运算

public class Solution {
    public int getSum(int a, int b) {
        if(b==0)
            return a;
        int carry = a & b;
        a = a^b;
        return getSum(a, carry<<1);
    }
}


Errors:






No comments:

Post a Comment