Created
November 7, 2019 18:15
-
-
Save HaiBV/c797daace9a1fd02eb301840148a0952 to your computer and use it in GitHub Desktop.
addTwoHugeNumbers
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
// Singly-linked lists are already defined with this interface: | |
// function ListNode(x) { | |
// this.value = x; | |
// this.next = null; | |
// } | |
// | |
function addTwoHugeNumbers(a, b) { | |
var sum = null, | |
tmp, | |
carry = 0, | |
x, y, | |
a = revertList(a), | |
b = revertList(b); | |
while (a || b || carry) { | |
x = a ? a.value : 0; | |
y = b ? b.value : 0; | |
tmp = new ListNode((carry + x + y) % 1e4); | |
tmp.next = sum; | |
sum = tmp; | |
carry = (carry + x + y) / 1e4 | 0; | |
if (a) a = a.next; | |
if (b) b = b.next; | |
} | |
return sum; | |
} | |
function revertList(head) { | |
let node = head, | |
previous, | |
tmp; | |
while (node) { | |
// save next before we overwrite node.next! | |
tmp = node.next; | |
// reverse pointer | |
node.next = previous; | |
// step forward in the list | |
previous = node; | |
node = tmp; | |
} | |
return previous; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're given 2 huge integers represented by linked lists. Each linked list element is a number from 0 to 9999 that represents a number with exactly 4 digits. The represented number might have leading zeros. Your task is to add up these huge integers and return the result in the same format.
Example
For a = [9876, 5432, 1999] and b = [1, 8001], the output should be
addTwoHugeNumbers(a, b) = [9876, 5434, 0].
Explanation: 987654321999 + 18001 = 987654340000.
For a = [123, 4, 5] and b = [100, 100, 100], the output should be
addTwoHugeNumbers(a, b) = [223, 104, 105].
Explanation: 12300040005 + 10001000100 = 22301040105.
https://app.codesignal.com/interview-practice/task/RvDFbsNC3Xn7pnQfH/description