Skip to content

Instantly share code, notes, and snippets.

@dance2die
Created April 14, 2019 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/3f11e90723410431aae22f18fb4b0124 to your computer and use it in GitHub Desktop.
Save dance2die/3f11e90723410431aae22f18fb4b0124 to your computer and use it in GitHub Desktop.
function addBits(v1, v2) {
const toNumberArray = str => str.split("").map(_ => +_);
const [a1, a2] = [toNumberArray(v1), toNumberArray(v2)];
// Add bits from right (least significant bit)
// to left (most significant bit)
const sum = a1.reduceRight((acc, a, i) => {
const b = a2[i];
// c => carry, s => sum
let [c, s] = [0, 0];
// Calculate the first bit
if (i === a1.length - 1) {
({ c, s } = halfAdder(a, b));
} else {
// Calculate the rest of the bits using the carry
const carry = (acc[0] && acc[0].c) || 0;
({ c, s } = fullAdder(a, b, carry));
}
return [{ c, s }, ...acc];
}, []);
// Build readable text
return sum.reduce(
(acc, { s, c }, i) => `${acc}${(i === 0 && c === 1 && "1") || ""}${s}`,
""
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment