371. Sum of Two Integers - Easy

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1

 

ref: solution with explanationyoutube video,用bit manipulation来计算两个数字之和

步骤:

用 & 找出进位,即carry = a & b

用 ^ 找出不同的bit,并将其赋值给a,a = a ^ b;

把carry左移一位并赋值给b, b = carry << 1;

不断循环直到 b = 0

e.g. a = 1, b = 3 -> a = 0001, b = 0011

carry = a & b = 0001 & 0011 = 0001, a = a ^ b = 0001 ^ 0011 = 0010, b = carry << 1 = 0001 << 1 = 0010

carry = a & b = 0010 & 0010 = 0010, a = a ^ b = 0010 ^ 0010 = 0000, b = carry << 1 = 0010 << 1 = 0100

carry = a & b = 0000 & 0100 = 0000, a = a ^ b = 0000 ^ 0100 = 0100, b = carry << 1 = 0000, return a = 0100 = 4

time: O(n), space: O(1)

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

 

posted @ 2018-12-19 15:35  fatttcat  阅读(82)  评论(0编辑  收藏  举报