1
2
3
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
Solution {
public
int
getSum(
int
a,
int
b) {
//第一种
while
(a!=
0
){
int
carry=(a&b)<<
1
;
b=a^b;
a=carry;
}
return
b;
递归计算
// if(b==0)return a;
// int carry=(a&b)<<1;
// int sum=a^b;
// return getSum(sum,carry);
}
}
|
其实针对第一种方法,看图中就明白了。一开始搞乱了。
异或求得是俩数的无进位加法,而进位只会发生在1+1的时候,所以可以用&运算符,但是要左移一位。
就是这样,学习了。第一次做位运算。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1890223