Calculate the sum of two integers a and b, but you are not allowed to use the operator+and-
1.位操作符
- 與 &:兩個位都為1,結果才為1
- 或 | :兩個位都為0,結果才為0
- 異或 ^:兩個位相同為0,相異為1
- 取反 ~: 0變1,1變0
- 左移 <<:左移若干位,高位丟棄,低位補0
- 右移 >>:右移若干位,對于無符號數 高位補0;有符號數分為算數右移(補符號位)和邏輯右移(補零)
位操作只用于整形數據
2.算法
class Solution{
public:
int add (int a, int b) {
while(a!=0 && b!=0){
int temp = a;
a = temp & b;
b = b ^ temp;
a = a << 1;
}
return a == 0?b:a;
}
};