题目名称

给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和

示例

输入:a = “11”, b = “1”
输出:”100”

题解

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let s = "", minus = 0,al = a.length - 1, bl = b.length - 1, ml = Math.max(al, bl)
for(let i = 0; i <= ml; i++) {
let l = minus
if(al - i >= 0) {
l += +a[al-i]
}
if(bl - i >= 0) {
l += +b[bl-i]
}
if(l >= 2) {
l -= 2
minus = 1
} else {
minus = 0
}
s = l + s
}
if(minus) {
s = 1 + s
}
return s
};