Leetcode67: 两个二进制字符串的求和

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”

思路1:先算出a,b求和的十进制数,再将十进制转换为二进制即可,思路简单,代码也比较简洁:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
       
        s = 0
        for i in range(len(a)):
            if a[i] == '1':
                s += 2**(len(a)-i-1)
        for i in range(len(b)):
            if b[i] == '1':
                s += 2**(len(b)-i-1)
        c = ''
        if s==0:
            return '0'
        while(s):     ##这几行就是把十进制转换为二进制,若想改为其他进制,则把余数改一下就可以了;
            d = s%2
            s = s//2
            c += str(d)
        return c[::-1]

思路2:一开始我对a,b两个字符串的每个字符从低位到高位分别求和,逢2进1,可以AC,但是判断边界条件比较麻烦,具体看代码:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        
        a = a[::-1]
        b = b[::-1]
        
        length = min(len(a), len(b))
        c = ''
        t = 0
        for i in range(length):
            if int(a[i]) + int(b[i]) + t >= 2:
                c += str(int(a[i]) + int(b[i]) + t-2)
                t = 1
            else:
                c += str(int(a[i]) + int(b[i]) + t)
                t = 0

        i = 0
        if len(a) > len(b):
            while (length + i < len(a) and t + int(a[length + i]) >= 2):
                c += str(t + int(a[length + i]) - 2)
                t = 1
                i += 1
            if length + i == len(a):
                if t ==1:
                    c += '1'
            else:
                c += str(t + int(a[length + i]))
                if length+i+1<len(a):
                    c += a[length + i+1:]
        else:
            while (length + i < len(b) and t + int(b[length + i]) >= 2):
                c += str(t + int(b[length + i]) - 2)
                t = 1
                i += 1
            if length + i == len(b):
                if t ==1:
                    c += '1'
            else:
                c += str(t + int(b[length + i]))
                if length + i + 1 < len(b):
                    c += b[length + i + 1:]
        return c[::-1]

猜你喜欢

转载自blog.csdn.net/Flying_sfeng/article/details/82952378