/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let f = [], h = []
for(let i = a.length>= b.length ? a.length - 1 : b.length - 1 ; i >= 0 ; i--) {
if(a.length>= b.length) {
f.push(a[i])
if(b[i]) {
h.push(b[i])
}
}else {
f.push(b[i])
if(a[i]) {
h.push(a[i])
}
}
}
let index = 0
for(let j = 0 ; j < f.length ; j++) {
if(h[j]) {
if(Number(h[j]) + Number(f[j]) + index >= 2) {
f[j] = Number(h[j]) + Number(f[j]) + index - 2
index = 1
}else {
f[j] = Number(h[j]) + Number(f[j]) + index
index = 0
}
}else if(index == 1) {
if(f[j]) {
if(Number(f[j]) + index == 2) {
f[j] = 0
index = 1
}else {
f[j] = index
index = 0
}
}
}
}
if(index == 1) f.push(1)
return f.reverse().join('')
};
力扣二进制求和
于 2023-09-20 09:43:17 首次发布