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.
不让用加法和减法,一看就是位运算的题目。
- a ^ b相当于没有进位的加法。因为(
1 ^ 1 = 0,0 ^ 0 = 0,1 ^ 0 = 1) - a & b相当于获得当前位的进位。因为(
1 & 1 = 1,0 & 0 = 0,1 & 0 = 0)
所以 a + b = a ^ b + (a & b) << 1, 我们可以反复做这个运算, 直到a & b == 0为止
代码如下:
|
|
当然还可以写成递归的形式
|
|