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

思路

  1. 模拟加法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var addBinary = function (a, b) {
const items = []
let inc = 0
let curIndex = 1
while (curIndex <= a.length || curIndex <= b.length || inc) {
let sum = inc
if (curIndex <= a.length) {
sum += Number(a[a.length - curIndex])
}
if (curIndex <= b.length) {
sum += Number(b[b.length - curIndex])
}
items.push(sum % 2)
inc = Math.floor(sum / 2)
++curIndex
}
return items.reverse().join('')
}