File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments