Leetcode刷题记录——67. 二进制求和

在这里插入图片描述
考虑设置进位标识符

0725更新

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if a == '':
            return b
        elif b == '':
            return a
        cura = len(a) - 1
        curb = len(b) - 1
        jinwei = 0
        res = ''
        while cura >= 0 or curb >= 0 or jinwei != 0:
            if cura < 0:
                aval = 0
            else:
                aval = int(a[cura])
            if curb < 0:
                bval = 0
            else:
                bval = int(b[curb])
            tempres = aval + bval + jinwei
            if tempres == 3:
                jinwei = 1
                tempres = 1
            elif tempres == 2:
                jinwei = 1
                tempres = 0
            else:
                jinwei = 0
            res = str(tempres) + res
            if cura >= 0:
                cura -= 1
            if curb >= 0:
                curb -= 1
        return res
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        while len(a) < len(b):
            a = '0' + a
        while len(a) > len(b):
            b = '0' + b 
        sumstr = str(int(a) + int(b))
        sumstr = [letter for letter in sumstr]
        length = len(sumstr)
        jinwei = False
        for i in range(length):
            cur = length - i - 1
            if sumstr[cur] == '2':
                if jinwei == True:
                    sumstr[cur] = '1'
                elif jinwei == False:
                    sumstr[cur] = '0' 
                jinwei = True
            elif sumstr[cur] == '1':
                if jinwei == True:
                    sumstr[cur] = '0'
                elif jinwei == False:
                    sumstr[cur] = '1'
                    jinwei = False
            elif sumstr[cur] == '0':
                if jinwei == False:
                    sumstr[cur] = '0' 
                elif jinwei == True:
                    sumstr[cur] = '1'
                jinwei = False
        res = ''
        for letter in sumstr:
            res += letter
        if jinwei == True:
            res = '1' + res
        return res

            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值