写在前面
计算机位运算相关概念
举例推演上面的结论:
关于负数的位移
-1
左移一位即扩大两倍之后应该变为-2
上述写法中,第一种和第三种写法是符合预期的,但是leetcode编译时第一种写法时会出现
runtime error: left shift of negative value -2147483648
leetcode好像不支持负数的左移?
所以干脆用第三种写法,将左移后的数转换成无符号整数。
具体的原理可能还需要进一步学习
class Solution {
public:
int add(int a, int b) {
while(b!=0){
int sum = a^b; // 无进位和
// 这里不支持负数左移 runtime error: left shift of negative value -2147483648
// 将左移后的数变为无符号数
int c = (unsigned int)(a&b)<<1; // 进位
a = sum;
b = c;
}
return a;
}
};