[LeetCode] Sum of Two Integers

371. Sum of Two Integers

Given two integers a and b, return the sum of the two integers without using the operators + and -.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int getSum(int a, int b) {
int upper = 0;
int res = 0;
for(int i = 0; i < 32 and (a or b); i++) {
int bit = 1<<i;
if(upper) {
if(a & bit and b & bit) res |= bit;
else if(!(a & bit) and !(b & bit)) {res |= bit; upper = 0;}
} else {
if(a & bit and b & bit) upper = 1;
else if(a & bit or b & bit) res |= bit;
}
a ^= bit;
b ^= bit;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/sum-of-two-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.