1 class Solution: 2 def baseNeg2(self, x): 3 res = [] 4 while x: 5 res.append(x & 1) 6 x = -(x >> 1) 7 if len(res) == 0: 8 return [0] 9 else: 10 return res[::-1] 11 #return "".join(map(str, res[::-1] or [0])) 12 13 def addNegabinary(self, arr1: 'List[int]', arr2: 'List[int]') -> 'List[int]': 14 num1 = 0 15 num2 = 0 16 len1 = len(arr1) 17 len2 = len(arr2) 18 for i in range(len1): 19 num1 += arr1[-(i+1)] * pow(-2,i) 20 for j in range(len2): 21 num2 += arr2[-(j+1)] * pow(-2,j) 22 23 return self.baseNeg2(num1+num2)
-2进制转10进制,10进制再转-2进制。