【leetcode】1073. Adding Two Negabinary Numbers
作者:互联网
题目如下:
Given two numbers
arr1
andarr2
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 numberarr
in array format is also guaranteed to have no leading zeros: eitherarr == [0]
orarr[0] == 1
.Return the result of adding
arr1
andarr2
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
解题思路:负二进制的计算问题。首先把arr1和arr2中较短的那个前面补零直到两者长度一样,由于计算会有进位的情况,因为是负进制,最多只能进两位,所以还需要在arr1和arr2前面补两个零。假设用carry表示进位的情况,那么显然carry的取值只能是0,-1,1。0表示不需要进位,-1表示进位的值和当前位数的值的符号不一致,而1表示1致。例如11 + 01,末位的两个1相加需要进位到倒数第二位,由于倒数第二位的符号和末位是不一致的,因此记carry=-1;又01 + 01,末位进位到倒数第三位,两者符号一致,所以carry为1。记v = arr1[i] + arr2[i],显然v只能是0,1,2三种取值,加上carry的取值,很轻松的可以得出如下关系:
代码如下:
class Solution(object): def addNegabinary(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ length = max(len(arr1), len(arr2)) arr1 = [0]*2 + [0] * (length - len(arr1)) + arr1 arr2 = [0]*2 + [0] * (length - len(arr2)) + arr2 res = [] carry = 0 for i in range(len(arr1)): inx = len(arr1) - i - 1 v = arr1[inx] + arr2[inx] #carry: 0,1,-1 ; v:0,1,2 if carry == 1 and v == 0: res = [1] + res carry = 0 elif carry == 1 and v == 1: res = [0] + res carry = -1 elif carry == 1 and v == 2: res = [1] + res carry = -1 elif carry == -1 and v == 0: res = [1] + res carry = 1 elif carry == -1 and v == 1: res = [0] + res carry = 0 elif carry == -1 and v == 2: res = [1] + res carry = 0 elif carry == 0 and v <= 1: res = [v] + res elif carry == 0 and v == 2: res = [0] + res carry = -1 while len(res) > 1: if res[0] == 0: res.pop(0) continue break return res
标签:Adding,elif,res,Two,len,1073,arr2,arr1,carry 来源: https://www.cnblogs.com/seyjs/p/11004379.html