Adding Two Negabinary Numbers Problem
Description
LeetCode Problem 1073.
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.
Example 1:
Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
Output: [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.
Example 2:
Input: arr1 = [0], arr2 = [0]
Output: [0]
Example 3:
Input: arr1 = [0], arr2 = [1]
Output: [1]
Constraints:
1 <= arr1.length, arr2.length <= 1000arr1[i]andarr2[i]are0or1arr1andarr2have no leading zeros
Solution
Approach: Digit-by-Digit Addition with a Signed Carry
Add the numbers the way we add on paper: from the least significant digit to the most significant one, keeping a carry. The only difference is how the carry works in base -2.
At position k the digit is worth (-2)^k, and the next position is worth (-2)^(k+1) = -2 · (-2)^k. Let x be arr1's digit plus arr2's digit plus the carry. x is between -1 and 3:
xis0or1: writex, the carry is0.xis2or3: two units at positionkare worth-1units at positionk + 1. Writex - 2and carry-1.xis-1: we cannot write a negative digit, but-1 · (-2)^k = (-2)^k + (-2)^(k+1). Write1and carry+1.
Keep going while either array has digits left or the carry is not zero. The digits come out least significant first, so reverse them at the end.
The tricky part is the leading zeros: positive and negative parts can cancel, as in [1,1] + [1] (-1 + 1), which produces [0,0]. Remove extra zeros from the top, but keep a single 0 when the result is zero.
Complexity: O(m + n) time, where m and n are the lengths of the arrays. O(m + n) space for the result.
class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
i, j = len(arr1) - 1, len(arr2) - 1
carry = 0
ans = [] # digits, least significant first
while i >= 0 or j >= 0 or carry:
x = carry
if i >= 0:
x += arr1[i]
if j >= 0:
x += arr2[j]
carry = 0
if x >= 2: # 2 * (-2)^k = -1 * (-2)^(k+1)
x -= 2
carry = -1
elif x == -1: # -1 * (-2)^k = (-2)^k + (-2)^(k+1)
x = 1
carry = 1
ans.append(x)
i, j = i - 1, j - 1
while len(ans) > 1 and ans[-1] == 0: # drop leading zeros, keep a lone 0
ans.pop()
return ans[::-1]