Problem
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.
Note:
- 1 <= arr1.length <= 1000
- 1 <= arr2.length <= 1000
- arr1 and arr2 have no leading zeros
- arr1[i] is 0 or 1
- arr2[i] is 0 or 1
解题思路
着一题算是Convert to Base -2这一题的升级版,但是原理是一致的,就是当我们遍历到某处时,如果该处的余数是负数,我们就需要将其改成正数,并在进位时加1。
代码如下:
为了方便处理,我们可以首先将数组反向,再将数据加到较长的数组上,然后循环向后处理。如果处理到最后一位后,进位不是0,就可能有两种情况。第一种是进位是1,那么直接添加到数组末尾即可,如果进位是-1,则需要在数组的末尾添加上两个1,因为我们依然需要将其变成整数。另外这里需要注意的是如果存在先导0的情况,我们需要将先导0移出数组。最后反向输出即可。
class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
arr1 = arr1[::-1]
arr2 = arr2[::-1]
if (len(arr1) > len(arr2)):
pass
else:
arr1, arr2 = arr2, arr1
for i in range(min(len(arr1), len(arr2))):
arr1[i] += arr2[i]
up = 0
for i in range(len(arr1)):
up, remaining = divmod(up + arr1[i], -2)
if remaining < 0:
remaining += 2
up += 1
arr1[i] = remaining
if up == 1:
arr1.append(up)
if up == -1:
arr1 += [1, 1]
while arr1 and arr1[-1] == 0:
arr1.pop(-1)
if len(arr1) == 0:
return [0]
return arr1[::-1]