File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # [ 67. 二进制求和] ( https://leetcode.cn/problems/add-binary/description/ )
2+
3+ > ** 日期** :2026-02-15
4+ > ** 所用时间** :12min
5+ > ** 知识点** :模拟
6+
7+ ## 1. 题目描述
8+
9+ 给定两个** 二进制字符串** ` a ` 和 ` b ` ,以二进制字符串的形式返回它们的和。
10+
11+ ** 示例 1:**
12+
13+ ```
14+ 输入:a = "11", b = "1"
15+ 输出:"100"
16+ 解释:11₂ + 1₂ = 100₂
17+ ```
18+
19+ ** 示例 2:**
20+
21+ ```
22+ 输入:a = "1010", b = "1011"
23+ 输出:"10101"
24+ 解释:1010₂ + 1011₂ = 10101₂
25+ ```
26+
27+ ** 提示:**
28+
29+ - ` 1 <= a.length, b.length <= 10^4 `
30+ - ` a ` 和 ` b ` 仅由字符 ` '0' ` 或 ` '1' ` 组成
31+ - 字符串如果不是 ` "0" ` ,则不包含前导零
32+
33+ ## 2. 从低位到高位模拟 + 进位
34+
35+ 从两个字符串的** 最低位** 开始,同时从右往左遍历,用变量 ` t ` 表示当前位的和(含进位)。每次加上 ` a[i] ` 、` b[j] ` 的数值,当前位结果为 ` t % 2 ` ,进位为 ` t // 2 ` ;当两串都走完且进位为 0 时结束。结果字符串每次把新的一位拼在左侧(或先逆序再反转)。
36+
37+ 复杂度分析:
38+
39+ - ** 时间复杂度** :$O(\max(n, m))$,其中 $n$、$m$ 为两串长度。
40+ - ** 空间复杂度** :$O(\max(n, m))$,用于存储结果字符串(不计返回值本身则为 $O(1)$ 额外空间)。
41+
42+ ** Python3**
43+
44+ ``` python
45+ class Solution :
46+ def addBinary (self , a : str , b : str ) -> str :
47+ ans = ' '
48+ t = 0
49+ i, j = len (a) - 1 , len (b) - 1
50+ while i >= 0 or j >= 0 or t:
51+ if i >= 0 :
52+ t += int (a[i])
53+ if j >= 0 :
54+ t += int (b[j])
55+ ans = str (t % 2 ) + ans
56+ t //= 2
57+ i -= 1
58+ j -= 1
59+ return ans
60+ ```
You can’t perform that action at this time.
0 commit comments