Skip to content

Commit 267f5c6

Browse files
authored
Create 371. Sum of Two Integers.java
1 parent 9907900 commit 267f5c6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

371. Sum of Two Integers.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// https://discuss.leetcode.com/topic/49771/java-simple-easy-understand-solution-with-explanation
2+
3+
// Iterative
4+
public int getSum(int a, int b) {
5+
if (a == 0) return b;
6+
if (b == 0) return a;
7+
8+
while (b != 0) {
9+
int carry = a & b;
10+
a = a ^ b;
11+
b = carry << 1;
12+
}
13+
14+
return a;
15+
}
16+
17+
// Iterative
18+
public int getSubtract(int a, int b) {
19+
while (b != 0) {
20+
int borrow = (~a) & b;
21+
a = a ^ b;
22+
b = borrow << 1;
23+
}
24+
25+
return a;
26+
}
27+
28+
// Recursive
29+
public int getSum(int a, int b) {
30+
return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
31+
}
32+
33+
// Recursive
34+
public int getSubtract(int a, int b) {
35+
return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
36+
}
37+
38+
// Get negative number
39+
public int negate(int x) {
40+
return ~x + 1;
41+
}

0 commit comments

Comments
 (0)