Adding Two Negabinary Numbers LeetCode solution in Java

1
class Solution {
2
public int[] addNegabinary(int[] arr1, int[] arr2) {
3

4
List<Integer> result = new ArrayList();
5
int pointer_1 = arr1.length - 1;
6
int pointer_2 = arr2.length - 1;
7

8
int carry = 0;
9
int current = 0;
10
int sum = 0;
11

12
while (pointer_1 >= 0 || pointer_2 >= 0) {
13

14
int a = (pointer_1 >= 0) ? arr1[pointer_1] : 0;
15
int b = (pointer_2 >= 0) ? arr2[pointer_2] : 0;
16

17
sum = a + b + carry;
18
if (sum == 3) {
19
current = 1;
20
carry = -1;
21
} else if (sum == 2) {
22
current = 0;
23
carry = -1;
24
} else if (sum == 1) {
25
current = 1;
26
carry = 0;
27
} else if (sum == 0) {
28
current = 0;
29
carry = 0;
30
} else if (sum == -1) {
31
current = 1;
32
carry = 1;
33
}
34

35
result.add(current);
36
pointer_1--;
37
pointer_2--;
38
}
39

40
if (carry != 0) result.add(1);
41
if (carry == -1) result.add(1);
42

43
// Removing leading zeros
44
int idx = result.size() - 1;
45
while (idx > 0 && result.get(idx) == 0) idx--;
46

47
// reversing the list and adding the result to an array
48
int len = idx + 1;
49
int[] negaBinary = new int[len];
50
for (int i = 0; i < len; i++) {
51
negaBinary[i] = result.get(idx);
52
idx--;
53
}
54

55
return negaBinary;
56
}
57
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0