## 题目描述

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.

## 解法一

### 思路

``````  00110011
+ 01010101
----------
10001000``````

``````  00110011
& 01010101
----------
00010001
<<
----------
00100010``````

``````  00110011
^ 01010101
----------
01100110``````

``````  00100010
+ 01100110
----------
10001000``````

``````     00110011
01010101
----------
& -> 00010001 << 1 -> 00100010
^ -> 01100110

00100010
01100110
----------
& -> 00100010 << 1 -> 01000100
^ -> 01000100

01000100
01000100
----------
& -> 01000100 << 1 -> 10001000
^ -> 00000000

10001000
00000000
----------
& -> 00000000
^ -> 10001000

output: 10001000``````

### Python

``````class Solution:
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
sum = (a ^ b) & mask
part = a & b
while part:
a = sum
b = (part << 1) & mask
sum = (a ^ b) & mask
part = a & b
if sum & 0x80000000:
sum -= 0x100000000
return sum``````

### Java

``````public class Solution {
public int getSum(int a, int b) {
int sum = a ^ b;
int part = a & b;
while (part != 0) {
int theA = sum;
int theB = part << 1;
sum = theA ^ theB;
part = theA & theB;
}
return sum;
}
}``````

### C++

``````class Solution {
public:
int getSum(int a, int b) {
int sum = a ^ b;
int part = a & b;
while (part) {
int theA = sum;
int theB = part << 1;
sum = theA ^ theB;
part = theA & theB;
}
return sum;
}
};``````