67. Add Binary [easy] (Python)

題目鏈接

https://leetcode.com/problems/add-binary/

題目原文

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

For example,
a = “11”
b = “1”
Return “100”.

題目翻譯

給定兩個二進制字符串,返回它們的和(也是二進制字符串)。
比如:a = “11”,b = “1”,返回 “100”。

思路方法

思路一

利用Python的進制轉換函數,先將兩個加數轉成10進制,再把和轉換成二進制返回即可。雖然速度還挺快的,但這麼做忽略了可能的大整數相加的細節(因爲Python幫你處理了)。

代碼

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return bin(int(a, 2) + int(b, 2))[2:]

思路二

從兩個字符串的最低位開始,一位一位的進行二進制相加,並保存進位,最終可以得到兩者的和的字符串。

代碼

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        res = ''
        i, j, plus = len(a)-1, len(b)-1, 0
        while i>=0 or j>=0 or plus==1:
            plus += int(a[i]) if i>= 0 else 0
            plus += int(b[j]) if j>= 0 else 0
            res = str(plus % 2) + res
            i, j, plus = i-1, j-1, plus/2
        return res

思路三

用遞歸實現,要注意,當兩個加數都是1時要進位。

代碼

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if not a or not b:
            return a if a else b
        if a[-1] == '1' and b[-1] == '1':
            return self.addBinary(self.addBinary(a[:-1], b[:-1]), '1') + '0'
        elif a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[:-1], b[:-1]) + '0'
        else:
            return self.addBinary(a[:-1], b[:-1]) + '1'

PS: 新手刷LeetCode,新手寫博客,寫錯了或者寫的不清楚還請幫忙指出,謝謝!
轉載請註明:http://blog.csdn.net/coder_orz/article/details/51706532

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章