-
Notifications
You must be signed in to change notification settings - Fork 17
/
SumOfTwoIntegersWithoutUsingPlusMinus.java
81 lines (74 loc) · 1.94 KB
/
SumOfTwoIntegersWithoutUsingPlusMinus.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package by.andd3dfx.numeric;
/**
* <pre>
* <a href="https://leetcode.com/problems/sum-of-two-integers/">Task description</a>
*
* Given two integers a and b, return the sum of the two integers without using the operators + and -.
*
* Example 1:
*
* Input: a = 1, b = 2
* Output: 3
*
* Example 2:
*
* Input: a = 2, b = 3
* Output: 5
* </pre>
*
* @see <a href="https://youtu.be/W_Vja_AFKFg">Video solution</a>
*/
public class SumOfTwoIntegersWithoutUsingPlusMinus {
/**
* Doesn't support the addition of negative numbers
*/
public static int getSum(int a, int b) {
int res = a;
for (var pos = 0; pos < 32; pos = incNthBit(pos, 0)) { // To avoid using `++` in expression :)
if ((b & (1 << pos)) != 0) {
res = incNthBit(res, pos);
}
}
return res;
}
static int incNthBit(int number, int n) {
var shifted_1 = 1 << n;
if ((number & shifted_1) == 0) {
return number | shifted_1;
}
number ^= shifted_1;
var n_plus_1 = incNthBit(n, 0); // To avoid using `+` in `n+1` expression :)
return incNthBit(number, n_plus_1);
}
/**
* <pre>
* 3 + 5 a + b
* --------------------
* 0b0011 a
* 0b0101 b
*
* 0b0110 a^b
* 0b0010 (a & b) << 1
* --------------------
* 0b0110 a2
* 0b0010 b2
*
* 0b0100 a2^b2
* 0b0100 (a2 & b2) << 1
* --------------------
* 0b0100 a3
* 0b0100 b3
*
* 0b0000 a3^b3
* 0b1000 (a3 & b3) << 1
* --------------------
* 0b0000 a4 = 0 => b4 - result
* 0b1000 b4 = 8
* </pre>
*/
public static int getSumOptimized(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
return getSumOptimized(a ^ b, (a & b) << 1);
}
}