二进制加法-Js
function add(a, b) {
let i = a.length;
let j = b.length;
let up = 0;
let res = [];
// console.log(i,j);
while (i > 0 || j > 0) {
let cur1 = a.charAt(i - 1) - 0
let cur2 = b.charAt(j - 1) - 0
let temp = cur1 + cur2 + up
if (temp > 1) {
up = 1
temp -= 2
} else {
up = 0
}
i--
j--
res.unshift(temp)
}
if (up !== 0) {
res.unshift(up)
}
return res.join('')
}
console.log(add('1010', '11'), '====');
结果 :

浙公网安备 33010602011771号