Leetcode 1148 Solution

This article provides solution to leetcode question 1148 (adding-two-negabinary-numbers)

https://leetcode.com/problems/adding-two-negabinary-numbers

Solution

class Solution:
    def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
        s = []

        rarr1 = list(reversed(arr1))
        rarr2 = list(reversed(arr2))

        i = 0
        while i < len(rarr1) or i < len(rarr2):
            s.append(0)

            if i < len(rarr1):
                s[-1] += rarr1[i]
            if i < len(rarr2):
                s[-1] += rarr2[i]

            i += 1

        carry = 0
        i = 0

        while i < len(s) or carry != 0:
            v = carry

            if i < len(s):
                v += s[i]
            else:
                s.append(0)

            if v % (-2) == 0:
                s[i] = 0
                carry = v // (-2)
            else:
                s[i] = 1
                carry = v // (-2) + 1

            i += 1

        i = len(s) - 1
        while i > 0 and s[i] == 0:
            s.pop()
            i -= 1

        s.reverse()

        return s