LeetCode67. 二进制求和

那年仲夏 提交于 2019-12-14 04:29:39

LeetCode67. 二进制求和

1.题目

给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。

2.示例

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

3.思路

①:使用字符方法来解决
②:处理成整数来解决

4.代码

class Solution(object):
		"""
		leetcode答案的代码copy过来的,没有去对齐就解决完问题,思路还是挺好的
		"""
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        ans, extra = '',0 
        i,j=len(a)-1,len(b)-1
        while i>=0 or j>=0:
            if i >= 0:
                extra += ord(a[i]) - ord('0')
            if j >= 0:
                extra += ord(b[j]) - ord('0')
            ans += str(extra % 2)
            extra //= 2
            i,j = i-1,j-1
        if extra == 1:
            ans += '1'
        return ans[::-1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!