• Leetcode 1073. 负二进制数相加(Adding Two Negabinary Numbers)


    题目

    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

    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.

    思路

    这是一个最简单的解题思路。先将-2进制的数组转为10进制,然后再将10进制相加的结果转回-2进制
    本题还有不少的优化空间,可以使用carry bit(进位位)来优化代码,以后有时间了来补上。

    Code

    class Solution:
        def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
            n1 = self.negabinaryToNum(arr1)
            n2 = self.negabinaryToNum(arr2)
            return self.numToNegabinary(n1 + n2)
        
        def negabinaryToNum(self, arr: List[int]) -> int:
            result = 0
            for i in range(len(arr)):
                result += arr[-(i+1)] * pow(-2, i)
            return result
        
        def numToNegabinary(self, num: int) -> List[int]:
            if num == 0:
                return [0]
            result = []
            while num:
                result.append(num&1)
                num = -(num >> 1)
            return result[::-1]
    
  • 相关阅读:
    1775. [国家集训队2010]小Z的袜子
    面试经典-分金条
    你的话信用度太低,说出来就像喝水一样容易
    uvalive 3971
    lua学习:使用Lua处理游戏数据
    每一次量体重。轻了就对自己说:瘦了。重了就对自己说: 胸部大了
    啊华北哦好咕~~(╯﹏╰)b
    啊别怪我好
    阿尔宾观海卫哦
    面试经典--两个房间 每间房间三盏灯
  • 原文地址:https://www.cnblogs.com/yufeng97/p/12593832.html
Copyright © 2020-2023  润新知