Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0653466

Browse files
committed
add 05
1 parent 09ac56f commit 0653466

File tree

1 file changed

+46
-0
lines changed
  • leetcode刷题/note/6月刷题

1 file changed

+46
-0
lines changed

‎leetcode刷题/note/6月刷题/05.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# No.67 二进制求和
2+
3+
难度:`easy`
4+
5+
给你两个二进制字符串,返回它们的和(用二进制表示)。
6+
7+
输入为 非空 字符串且只包含数字 1 和 0。
8+
9+
## 示例
10+
11+
```
12+
示例 1:
13+
14+
输入: a = "11", b = "1"
15+
输出: "100"
16+
--------
17+
示例 2:
18+
19+
输入: a = "1010", b = "1011"
20+
输出: "10101"
21+
```
22+
23+
### 解题思路
24+
25+
将两个字符串较短的用 00 补齐,使得两个字符串长度一致,然后从末尾进行遍历计算,得到最终结果。
26+
27+
```javascript
28+
/**
29+
* @param {string} a
30+
* @param {string} b
31+
* @return {string}
32+
*/
33+
var addBinary = function(a, b) {
34+
let ans = "";
35+
let ca = 0;
36+
for(let i = a.length - 1, j = b.length - 1;i >= 0 || j >= 0; i--, j--) {
37+
let sum = ca;
38+
sum += i >= 0 ? parseInt(a[i]) : 0;
39+
sum += j >= 0 ? parseInt(b[j]) : 0;
40+
ans += sum % 2;
41+
ca = Math.floor(sum / 2);
42+
}
43+
ans += ca == 1 ? ca : "";
44+
return ans.split('').reverse().join('');
45+
};
46+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /