67. Add Binary

2,530次阅读
没有评论

共计 372 个字符,预计需要花费 1 分钟才能阅读完成。

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

解法:

class Solution:
    def addBinary(self, a: 'str', b: 'str') -> 'str':
        copy_a=a
        copy_b=b
        if len(a)<=len(b):
            copy_a='0'*(len(copy_b)-len(copy_a))+copy_a
        else:
            copy_b='0'*(len(copy_a)-len(copy_b))+copy_b
            
        result=''
        flag=0
        for x in range(len(copy_a)-1,-1,-1):
            tmp=int(copy_a[x])+int(copy_b[x])+flag
            
            if tmp>1:
                flag=1
            else:
                flag=0
            
            result=str(tmp%2)+result
        if flag==1:
            result='1'+result
        return result
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-02-17发表,共计372字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码