Last active
January 2, 2019 05:34
-
-
Save j-quelly/2684c3e0726fc53665a6df5762d9e37f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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