LeetCode67:Add Binary

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"

LeetCode:链接

设置进位flag,同时也作为每次相加的和。然后循环,条件是flag==1或者两个字符串有一个没有遍历完成。然后每次flag+各字符串当前坐标下的值-‘0’;最后,将flag%2转换为字符加到要返回的string前面,并且flag/2获取下一次的进位值。最后循环结束,返回string。

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        end1 = len(a) - 1
        end2 = len(b) - 1
        flag = 0
        result = ''
        while end1 >= 0 or end2 >= 0 or flag == 1:
            if end1 >= 0:
                '''必须用ord(a[end1]) - ord('0')表示数字'''
                flag += ord(a[end1]) - ord('0')
                end1 -= 1
            if end2 >= 0:
                flag += ord(b[end2]) - ord('0')
                end2 -= 1
            result = str(flag%2) + result
            flag /= 2
        return result


 

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84099418