[LeetCode] Adding Two Negabinary Numbers

1073. Adding Two Negabinary Numbers

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

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
class Solution {
public:
vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) {
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
int add = 0, sz1 = arr1.size(), sz2 = arr2.size(), end = max(sz1,sz2);
vector<int>& res = arr1.size() > arr2.size() ? arr1 : arr2;
for(int i = 0 ; i < end; i++) {
add *= -1;
if(i < sz1) add += arr1[i];
if(i < sz2) add += arr2[i];

switch (add) {
case 3: res[i] = 1; add = 1; break;
case 2: res[i] = 0; add = 1; break;
case 1: res[i] = 1; add = 0; break;
case 0: res[i] = 0; add = 0; break;
case -1: res[i] = 1; add = -1; break;
}
}
if(add) {res.push_back(1); res.push_back(1);}
while(!res.back() && res.size() >= 2)
res.pop_back();
reverse(res.begin(), res.end());
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/27/PS/LeetCode/adding-two-negabinary-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.