leetcode python3 简单题67. Add Binary

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第六十七题

(1)题目
英文:
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.

中文:
给你两个二进制字符串,返回它们的和(用二进制表示)。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-binary

(2)解法
① 先转int相加,再转回binary(耗时:40ms,内存:13.7M)

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a,2) + int(b,2))[2:]

注意:
1.bin输出的二进制是带有标识ob的,所以用[2:]去除。
2.int(a,2),是直接将字符串a转为了二进制的对应的整数,此时的a不能是一般的数字。

② 逐位相加(耗时:56ms,内存:13.8M)

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if len(a) < len(b): 
            a, b = b, a
        n = len(a)
        b = '0'*(n - len(b))+b
        res = ''
        forward_flag = 0
        for indx in range(n):
            a_1 = int(a[-indx-1])
            b_1 = int(b[-indx-1])
            res = str((a_1 + b_1 + forward_flag) % 2)+res
            forward_flag = (a_1 + b_1 + forward_flag) // 2
        if forward_flag == 1:
            res = '1' + res
        return res

注意:
1.a,b的交换在python中可以直接交换,也可以使用中间变量法:

tmp=a
a=b
b=tmp

2.给b添0补齐的时候,不能使用b+=的形式,因为必须是在b的左边补0、
3.最后的if forward_flag == 1:是用于最高位还有进位的情况。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值