アイデア:
コード:
class Solution {
public:
int add(int a, int b) {
if (a == 0 || b == 0) {
return a == 0 ? b : a;
}
int sum = 0, carry = 0;
while (b != 0) {
// 当没有进位的时候退出循环
sum = a ^ b;
carry = (unsigned int) (a & b) << 1; //Leetcode C++ 不允许负数进行左移操作,故要加 unsigned int,其他的编译器是可以的对负数进行左移
a = sum;
b = carry;
}
return a;
}
};