原题
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
}
二进制求和算法解析
283

被折叠的 条评论
为什么被折叠?



