跳到主要内容

Add Binary

描述

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"
b = "1"

Return 100.

分析

手工模拟大整数加法。

代码

# Add Binary
# Time Complexity: O(max(m,n)), Space Complexity: O(max(m,n))
def addBinary(a: str, b: str) -> str:
result = []
i, j = len(a) - 1, len(b) - 1
carry = 0
while i >= 0 or j >= 0 or carry:
x = int(a[i]) if i >= 0 else 0
y = int(b[j]) if j >= 0 else 0
total = x + y + carry
result.append(str(total % 2))
carry = total // 2
i, j = i - 1, j - 1
return ''.join(result[::-1])

相关题目