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
andarr2
have no leading zerosarr1[i]
is0
or1
arr2[i]
is0
or1
class Solution(object):
def addNegabinary(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
def get(a):
res=0
for i in a:
res*=-2
if i==1: res+=1
return res
def convert(n):
if n==0: return [0]
res=[]
bit=0
while n!=0:
if n%2==1:
res.append(1)
# n-=(1 if bit%2==0 else -1)
n-=1
else:
res.append(0)
n=n//-2
bit+=1
return res[::-1]
n1=get(arr1)
n2=get(arr2)
# print(n1,n2)
return convert(n1+n2)