Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
class Solution {
public int getSum(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
// a = 010 ; b = 011
while (b != 0) {
int carry = a & b; //carry = 010 // carry =000 //a & b 可以得到 a 和 b 的需進位結果
a = a ^ b; //a = 001 // a = 101 //a ^ b 可以得到 a 和 b 的不進位加法結果
b = carry << 1; //b = 100 / /b = 000 //進位進一位
}
return a; //101
}
}
Time: O(k) (k為二進制的位數)
Space: O(1)