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 29 30 31 32 33 34 35 36 37 38 39
|
var addBinary = function(a, b) { if (a.length > b.length) { return addBinary(b, a); }
const len = b.length; let [count, incremental, result] = [len - 1, 0, []];
[a] = [a.padStart(len, '0')];
while (count >= 0) { const [v1, v2] = [ a[count] ? +(a[count]) : 0, b[count] ? +(b[count]) : 0, ];
const temp = v1 + v2 + incremental;
result.unshift( temp > 2 ? 1 : temp === 2 ? 0 : temp ); incremental = temp >= 2 ? 1 : 0;
count--; }
incremental && (result.unshift(incremental));
return result.join(''); };
|