File tree 1 file changed +11
-10
lines changed
scripts/algorithms/A/Adding Two Negabinary Numbers
1 file changed +11
-10
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 1 ms (Top 100.00%) | Memory: 42.4 MB (Top 98.61%)
1
2
class Solution {
2
3
public int [] addNegabinary (int [] arr1 , int [] arr2 ) {
3
-
4
+
4
5
List <Integer > result = new ArrayList ();
5
6
int pointer_1 = arr1 .length -1 ;
6
7
int pointer_2 = arr2 .length -1 ;
7
8
8
9
int carry = 0 ;
9
10
int current = 0 ;
10
11
int sum = 0 ;
11
-
12
+
12
13
while (pointer_1 >= 0 || pointer_2 >= 0 ){
13
-
14
+
14
15
int a = (pointer_1 >=0 )? arr1 [pointer_1 ]: 0 ;
15
16
int b = (pointer_2 >=0 )? arr2 [pointer_2 ]: 0 ;
16
-
17
+
17
18
sum = a +b +carry ;
18
19
if (sum == 3 ){
19
20
current = 1 ; carry = -1 ;
@@ -31,31 +32,31 @@ else if(sum == -1)
31
32
{
32
33
current = 1 ; carry = 1 ;
33
34
}
34
-
35
+
35
36
result .add (current );
36
37
pointer_1 --;
37
38
pointer_2 --;
38
39
}
39
-
40
+
40
41
if (carry != 0 )
41
42
result .add (1 );
42
43
if (carry == -1 )
43
44
result .add (1 );
44
-
45
+
45
46
// Removing leading zeros
46
47
int idx = result .size ()-1 ;
47
48
while (idx > 0 && result .get (idx ) == 0 )
48
49
idx --;
49
-
50
+
50
51
// reversing the list and adding the result to an array
51
52
int len = idx +1 ;
52
53
int [] negaBinary = new int [len ];
53
54
for (int i =0 ; i <len ; i ++){
54
55
negaBinary [i ] = result .get (idx );
55
56
idx --;
56
57
}
57
-
58
+
58
59
return negaBinary ;
59
-
60
+
60
61
}
61
62
}
You can’t perform that action at this time.
0 commit comments