Skip to content

Commit 9714df6

Browse files
authored
Create adding-two-negabinary-numbers.cpp
1 parent e56279b commit 9714df6

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

C++/adding-two-negabinary-numbers.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) {
7+
vector<int> result;
8+
int carry = 0, i = arr1.size() - 1, j = arr2.size() - 1;
9+
while (i >= 0 || j >= 0 || carry) {
10+
if (i >= 0) {
11+
carry += arr1[i--];
12+
}
13+
if (j >= 0) {
14+
carry += arr2[j--];
15+
}
16+
result.emplace_back(carry & 1);
17+
carry = -(carry >> 1);
18+
}
19+
while (result.size() > 1 && result.back() == 0) {
20+
result.pop_back();
21+
}
22+
reverse(result.begin(), result.end());
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)