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]
posted @ 2020-03-29 18:14  下雨不刮风  阅读(187)  评论(0编辑  收藏  举报