【leetcode 简单】第十六题 二进制求和

本文介绍了一种解决二进制字符串相加问题的方法。通过两种不同的实现方式,一种是手动处理每一位的进位和相加操作,另一种是利用Python内置函数进行转换计算。这两种方法都能有效地将两个二进制字符串相加并返回结果。

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

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

示例 2:

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

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        a_len=len(a)
        b_len=len(b)
        result=''
        next ='0'
        while a_len and b_len :
            if sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 3:
                result +='1'
                next = '1'
            elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 2:
                result+='0'
                next ='1'
            elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 0:
                result+='0'
                next ='0'
            elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) < 2:
                result+='1'
                next ='0'
            a_len-=1
            b_len-=1
        new = a[:a_len] if a_len > b_len else b[:b_len]
        if new:
            for i in new[::-1]:
                if sum([int(next),int(i)]) == 2:
                    result+='0'
                    next ='1'
                elif sum([int(next),int(i)]) == 1:
                    result+='1'
                    next ='0'
                else:
                    result+='0'
                    next ='0'
        if next != 0:
            result+=next
        return (result[::-1])
class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """

        return format(int(a,2)+int(b,2),"b")

 

转载于:https://www.cnblogs.com/flashBoxer/p/9458240.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值