40
40
41
41
<!-- 这里可写通用的实现逻辑 -->
42
42
43
- 模拟笔算加法的过程,注意进位
43
+ ** 方法一:模拟**
44
+
45
+ 我们用一个变量 $carry$ 记录当前的进位,用两个指针 $i$ 和 $j$ 分别指向 $a$ 和 $b$ 的末尾,从末尾到开头逐位相加即可。
46
+
47
+ 时间复杂度 $O(\max(m, n))$,其中 $m$ 和 $n$ 分别为字符串 $a$ 和 $b$ 的长度。空间复杂度 $O(1)$。
44
48
45
49
<!-- tabs:start -->
46
50
51
55
``` python
52
56
class Solution :
53
57
def addBinary (self , a : str , b : str ) -> str :
54
- x, y = len (a) - 1 , len (b) - 1
55
- arr = []
56
- carry = 0
57
- while x >= 0 or y >= 0 :
58
- if x >= 0 :
59
- if a[x] == ' 1' :
60
- carry += 1
61
- x -= 1
62
- if y >= 0 :
63
- if b[y] == ' 1' :
64
- carry += 1
65
- y -= 1
66
- arr.append(chr ((carry & 1 ) + ord (' 0' )))
67
- carry >>= 1
68
- if carry == 1 :
69
- arr.append(' 1' )
70
- return ' ' .join(reversed (arr))
58
+ return bin (int (a, 2 ) + int (b, 2 ))[2 :]
59
+ ```
60
+
61
+ ``` python
62
+ class Solution :
63
+ def addBinary (self , a : str , b : str ) -> str :
64
+ ans = []
65
+ i, j, carry = len (a) - 1 , len (b) - 1 , 0
66
+ while i >= 0 or j >= 0 or carry:
67
+ carry += (0 if i < 0 else int (a[i])) + (0 if j < 0 else int (b[j]))
68
+ carry, v = divmod (carry, 2 )
69
+ ans.append(str (v))
70
+ i, j = i - 1 , j - 1
71
+ return ' ' .join(ans[::- 1 ])
71
72
```
72
73
73
74
### ** Java**
@@ -77,93 +78,103 @@ class Solution:
77
78
``` java
78
79
class Solution {
79
80
public String addBinary (String a , String b ) {
80
- int x = a. length() - 1 , y = b. length() - 1 ;
81
- StringBuilder builder = new StringBuilder ();
82
- int carry = 0 ;
83
- while (x >= 0 || y >= 0 ) {
84
- if (x >= 0 ) {
85
- if (a. charAt(x) == ' 1' ) {
86
- carry += 1 ;
87
- }
88
- x-- ;
89
- }
90
- if (y >= 0 ) {
91
- if (b. charAt(y) == ' 1' ) {
92
- carry += 1 ;
93
- }
94
- y-- ;
95
- }
96
- builder. append((char ) ((carry & 1 ) + ' 0' ));
97
- carry >> = 1 ;
81
+ var sb = new StringBuilder ();
82
+ int i = a. length() - 1 , j = b. length() - 1 ;
83
+ for (int carry = 0 ; i >= 0 || j >= 0 || carry > 0 ; -- i, -- j) {
84
+ carry += (i >= 0 ? a. charAt(i) - ' 0' : 0 ) + (j >= 0 ? b. charAt(j) - ' 0' : 0 );
85
+ sb. append(carry % 2 );
86
+ carry /= 2 ;
98
87
}
99
- if (carry == 1 ) {
100
- builder. append(' 1' );
101
- }
102
- return builder. reverse(). toString();
88
+ return sb. reverse(). toString();
103
89
}
104
90
}
105
91
```
106
92
93
+ ### ** C++**
94
+
95
+ ``` cpp
96
+ class Solution {
97
+ public:
98
+ string addBinary(string a, string b) {
99
+ string ans;
100
+ int i = a.size() - 1, j = b.size() - 1;
101
+ for (int carry = 0; i >= 0 || j >= 0 || carry; --i, --j) {
102
+ carry += (i >= 0 ? a[ i] - '0' : 0) + (j >= 0 ? b[ j] - '0' : 0);
103
+ ans.push_back((carry % 2) + '0');
104
+ carry /= 2;
105
+ }
106
+ reverse(ans.begin(), ans.end());
107
+ return ans;
108
+ }
109
+ };
110
+ ```
111
+
107
112
### **Go**
108
113
109
114
```go
110
115
func addBinary(a string, b string) string {
111
- x , y := len (a)-1 , len (b)-1
112
- var builder strings.Builder
113
- carry := 0
114
- for x >= 0 || y >= 0 {
115
- if x >= 0 {
116
- if a[x] == ' 1' {
117
- carry += 1
118
- }
119
- x--
116
+ i, j := len(a)-1, len(b)-1
117
+ ans := []byte{}
118
+ for carry := 0; i >= 0 || j >= 0 || carry > 0; i, j = i-1, j-1 {
119
+ if i >= 0 {
120
+ carry += int(a[i] - '0')
120
121
}
121
- if y >= 0 {
122
- if b[y] == ' 1' {
123
- carry += 1
124
- }
125
- y--
122
+ if j >= 0 {
123
+ carry += int(b[j] - '0')
126
124
}
127
- builder. WriteRune ( rune (carry& 1 + ' 0' ))
128
- carry >>= 1
125
+ ans = append(ans, byte (carry%2+ '0'))
126
+ carry /= 2
129
127
}
130
- if carry == 1 {
131
- builder. WriteRune ( ' 1 ' )
128
+ for i, j := 0, len(ans)-1; i < j; i, j = i+1, j- 1 {
129
+ ans[i], ans[j] = ans[j], ans[i]
132
130
}
133
- bytes := []byte (builder.String ())
134
- for i , j := 0 , len (bytes)-1 ; i < j; i, j = i+1 , j-1 {
135
- bytes[i], bytes[j] = bytes[j], bytes[i]
136
- }
137
- return string (bytes)
131
+ return string(ans)
138
132
}
139
133
```
140
134
141
- ### ** C++**
135
+ ### ** TypeScript**
136
+
137
+ ``` ts
138
+ function addBinary(a : string , b : string ): string {
139
+ let i = a .length - 1 ;
140
+ let j = b .length - 1 ;
141
+ let ans: number [] = [];
142
+ for (let carry = 0 ; i >= 0 || j >= 0 || carry ; -- i , -- j ) {
143
+ carry += (i >= 0 ? a [i ] : ' 0' ).charCodeAt (0 ) - ' 0' .charCodeAt (0 );
144
+ carry += (j >= 0 ? b [j ] : ' 0' ).charCodeAt (0 ) - ' 0' .charCodeAt (0 );
145
+ ans .push (carry % 2 );
146
+ carry >>= 1 ;
147
+ }
148
+ return ans .reverse ().join (' ' );
149
+ }
150
+ ```
142
151
143
- ``` cpp
144
- class Solution {
145
- public:
146
- string addBinary(string a, string b) {
147
- string res;
148
- int carry = 0;
149
-
150
- int i = a.size() - 1;
151
- int j = b.size() - 1;
152
-
153
- while (i >= 0 || j >= 0) {
154
- int digitA = i >= 0 ? a.at(i--) - '0' : 0;
155
- int digitB = j >= 0 ? b.at(j--) - '0' : 0;
156
- int sum = digitA + digitB + carry;
157
- carry = sum >= 2 ? 1 : 0;
158
- sum = sum >= 2 ? sum - 2 : sum;
159
- res += to_string(sum);
152
+ ### ** Rust**
153
+
154
+ ``` rust
155
+ impl Solution {
156
+ pub fn add_binary (a : String , b : String ) -> String {
157
+ let mut i = a . len () as i32 - 1 ;
158
+ let mut j = b . len () as i32 - 1 ;
159
+ let mut carry = 0 ;
160
+ let mut ans = String :: new ();
161
+ let a = a . as_bytes ();
162
+ let b = b . as_bytes ();
163
+ while i >= 0 || j >= 0 || carry > 0 {
164
+ if i >= 0 {
165
+ carry += a [i as usize ] - b '0' ;
166
+ i -= 1 ;
167
+ }
168
+ if j >= 0 {
169
+ carry += b [j as usize ] - b '0' ;
170
+ j -= 1 ;
171
+ }
172
+ ans . push_str (& (carry % 2 ). to_string ());
173
+ carry /= 2 ;
160
174
}
161
-
162
- if (carry == 1 ) res.push_back(' 1' );
163
- reverse (res.begin(), res.end());
164
- return res;
175
+ ans . chars (). rev (). collect ()
165
176
}
166
- };
177
+ }
167
178
```
168
179
169
180
### ** ...**
0 commit comments