LeetCode 题解工作台
二进制求和
给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 提示: 1 4 a 和 b 仅由字符 '0' 或 '1' 组成…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
我们用一个变量 记录当前的进位,用两个指针 和 分别指向 和 的末尾,从末尾到开头逐位相加即可。 时间复杂度 $O(\max(m, n))$,其中 和 分别为字符串 和 的长度。空间复杂度 $O(\max(m, n))$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。
示例 1:
输入:a = "11", b = "1" 输出:"100"
示例 2:
输入:a = "1010", b = "1011" 输出:"10101"
提示:
1 <= a.length, b.length <= 104a和b仅由字符'0'或'1'组成- 字符串如果不是
"0",就不含前导零
解题思路
方法一:模拟
我们用一个变量 记录当前的进位,用两个指针 和 分别指向 和 的末尾,从末尾到开头逐位相加即可。
时间复杂度 ,其中 和 分别为字符串 和 的长度。空间复杂度 。
class Solution:
def addBinary(self, a: str, b: str) -> str:
ans = []
i, j, carry = len(a) - 1, len(b) - 1, 0
while i >= 0 or j >= 0 or carry:
carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j]))
carry, v = divmod(carry, 2)
ans.append(str(v))
i, j = i - 1, j - 1
return "".join(ans[::-1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you handle carry properly when adding binary digits?
- question_mark
Can you optimize the solution for large input sizes?
- question_mark
Will you account for cases where the binary strings have different lengths?
常见陷阱
外企场景- error
Ignoring the carry during addition can lead to incorrect results.
- error
Not managing string length differences properly may cause out-of-bounds errors.
- error
Forgetting to remove leading zeros from the final result can lead to invalid outputs.
进阶变体
外企场景- arrow_right_alt
Add Two Binary Strings with Overflow Handling
- arrow_right_alt
Multiply Binary Numbers
- arrow_right_alt
Convert Binary Sum to Decimal and Then Binary