67. 二进制求和 @Python@Go

二进制求和算法解析

原题

https://leetcode.cn/problems/add-binary/description/

思路

模拟, 从右向左遍历

复杂度

时间:O(n)
空间:O(n)

Python代码

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        ans = ''
        i = len(a) - 1
        j = len(b) - 1 
        carry = 0 
        while i >= 0 or j >= 0 or carry > 0:
            if i >= 0:
                carry += int(a[i])
                i -= 1 
            if j >= 0:
                carry += int(b[j])
                j -= 1 
            digit = carry % 2 
            carry //= 2
            ans = str(digit) + ans 
        return ans

Go代码

func addBinary(a string, b string) string {
	var ans string
	i, j := len(a)-1, len(b)-1
	carry := 0
	for i >= 0 || j >= 0 || carry > 0 {
		if i >= 0 {
			carry += int(a[i] - '0')
			i--
		}
		if j >= 0 {
			carry += int(b[j] - '0')
			j--
		}
		digit := carry % 2
		carry /= 2
		ans = string('0'+digit) + ans
	}
	return ans
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值