Adding Two Negabinary Numbers

Add base -2 numbers digit-by-digit — borrow propagates differently; trim leading zeros.

Medium
Time O(m + n) Space O(m + n)
LeetCode
5 min read
math array

Problem#

Two numbers are given as digit arrays in base -2 (MSB first, digits 0/1). Return their sum in the same form.

Examples#

  • [1,1,1,1,1], [1,0,1][1,0,0,0,0] (21 + (-3) = 18 = “10100” in base -2… wait — 11 + (-3) → 8).
  • [1,1,1,1,1], [1,0,1][1,0,0,0,0].
  • [1,0,1], [1][1,0,0].

Constraints#

  • 1 <= arr1.length, arr2.length <= 1000.

Approach#

Walk from LSB. Sum is a + b + carry. In base -2, the digit at position i is s mod -2… but easier: use signed carry. After adding, if s >= 2, set digit to s - 2 and carry -1. If s < 0, set digit to s + 2 and carry +1. Trim leading zeros.

Solution#

Adding Two Negabinary Numbers
class Solution {
public:
vector<int> addNegabinary(vector<int>& a, vector<int>& b) {
vector<int> out;
int i = a.size() - 1, j = b.size() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry) {
int x = (i >= 0) ? a[i--] : 0;
int y = (j >= 0) ? b[j--] : 0;
int s = x + y + carry;
if (s >= 2) { s -= 2; carry = -1; }
else if (s < 0) { s += 2; carry = 1; }
else carry = 0;
out.push_back(s);
}
while (out.size() > 1 && out.back() == 0) out.pop_back();
reverse(out.begin(), out.end());
return out;
}
};

Editorial#

In base -2, weight of position i is (-2)^i. The carry going to the next-higher position is negated relative to standard binary — that’s why exceeding 2 produces a -1 carry and going negative produces a +1 carry. Both rules keep each digit in {0, 1}.

Complexity#

  • Time: O(m + n).
  • Space: O(m + n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.