Friday, September 15, 2017

371. Sum of Two Integers

算法很有意思

http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/
5.07 %
class Solution {
    public int getSum(int a, int b) {
        int sum = 0;
        int carry = 0;
        while (b != 0) {
            carry = (a & b) << 1; // 0 + 0 -> 0, 1 + 1 -> 10
            a = a ^ b; // add without carry
            b = carry;
        }
        return a;
    }
}

No comments:

Post a Comment