leetcode 每日一题 67. 二进制求和

逐位计算

思路:

遍历字符串,逐位加和,用一个变量记录是否产生进位。

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        res = ''
        if len(a)<len(b):
            a,b = b,a 
        temp = 0
        for i in range(1,len(a)+1):
            if i <=len(b):
                tnum = int(a[-i]) + int(b[-i]) +temp
                res += str(tnum%2)
                temp = tnum//2
            else:
                tnum = int(a[-i])+temp
                res += str(tnum%2)
                temp = tnum//2
        if temp == 1:
            res += '1'   
        return res[::-1]

 

posted @ 2020-06-08 18:07  nil_f  阅读(107)  评论(0)    收藏  举报