LeetCode解题分享:1073. Adding Two Negabinary Numbers

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. 1 <= arr1.length <= 1000
  2. 1 <= arr2.length <= 1000
  3. arr1 and arr2 have no leading zeros
  4. arr1[i] is 0 or 1
  5. 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]
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值