Skip to content

Instantly share code, notes, and snippets.

@j-quelly
Last active January 2, 2019 05:34
Show Gist options
  • Save j-quelly/2684c3e0726fc53665a6df5762d9e37f to your computer and use it in GitHub Desktop.
Save j-quelly/2684c3e0726fc53665a6df5762d9e37f to your computer and use it in GitHub Desktop.
// Definition for singly-linked list:
// function ListNode(x) {
// this.value = x;
// this.next = null;
// }
//
function getNumber(list) {
let current = list;
let num = [];
while (current !== null) {
num.push(current.value);
current = current.next;
}
return num;
}
function addTwoHugeNumbers(a, b) {
const A = getNumber(a).reverse();
const B = getNumber(b).reverse();
const largest = A.length > B.length ? A : B;
let sum = 0;
let carry = 0;
const result = [];
largest.forEach((num, index) => {
const smallest = A.length > B.length ? B : A;
const adder = smallest[index] || 0;
sum = num + adder;
if (carry) {
sum += +carry;
}
const sumLen = sum.toString().length;
if (sumLen > 4) {
const carryLen = sumLen - 4;
carry = +sum.toString().slice(0, carryLen);
const thousands = +sum.toString().slice(carry, sum.length);
result.push(thousands ? thousands : 0);
} else {
carry = 0;
if (sum) {
result.push(sum);
} else {
result.push(largest[index]);
}
}
});
if (carry) {
result.push(carry);
}
return result.reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment