用异或和与左移,实现加法
class Solution {
public int add(int a, int b) {
while(b != 0){
int c = (a&b)<<1;
a ^= b;
b = c;
}
return a;
}
}
这样写,结果好像是对的,但是稍微大一点就超时了,,还不是很理解
理解了,因为下一轮想相加的是 n 和 c,而不是a b,所以要重新赋值处理
class Solution {
public int add(int a, int b) {
int res = 0;
int n = a, c = b;
while(c != 0){
n = a ^ b;
c = (a&b) << 1;
res = n^c;
}
return res;
}
}