Array -67 binary sum

1. Topic

Given two binary string, and return to their (expressed in binary).
And a non-empty input string contains only numbers 0 and 1.

Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"

2. Ideas

(1) summing the binary to decimal conversion.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return '{0:b}'.format(int(a, 2) + int(b, 2))

(2) adding bit by bit
security bit addition, the carry flag.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        n = max(len(a), len(b))
        a, b = a.zfill(n), b.zfill(n)   # 右对齐,填充 ‘0’
        carry = 0
        anser = []
        for i in range(n-1, -1, -1):
            if a[i] == '1':
                carry += 1
            if b[i] == '1':
                carry += 1

            if carry % 2:   # 判断是否进位   1%2 = 1; 2%2=0; 0%2=0
                anser.append('1')
            else:
                anser.append('0')
            
            carry //= 2  # 进位标志,向前进一位。
        
        if carry == 1:
            anser.append('1')
        anser.reverse()
        return ''.join(anser)

Published 41 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/niuchi2570/article/details/104503794