67. Add Binary

1,315次阅读
没有评论
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:

<strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"

Example 2:

<strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "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
            
admin
版权声明:本站原创文章,由admin2019-02-17发表,共计372字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)