Created
August 13, 2020 21:36
-
-
Save myTerminal/afa013b1e5bed6feaa719b020b7f1d59 to your computer and use it in GitHub Desktop.
Addition of two linked-lists as non-negative integers.
This file contains 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
/* | |
You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. | |
Example: | |
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) | |
Output: 7 -> 0 -> 8 | |
Explanation: 342 + 465 = 807. | |
*/ | |
class Node { | |
constructor(val, next) { | |
this.value = val; | |
this.next = next; | |
} | |
} | |
const numberOne = new Node( | |
2, | |
new Node( | |
4, | |
new Node( | |
3 | |
) | |
) | |
); | |
const numberTwo = new Node( | |
5, | |
new Node( | |
6, | |
new Node( | |
4 | |
) | |
) | |
); | |
const addReverseLists = (one, two) => { | |
let carry = 0; | |
let leftCurrent = one; | |
let rightCurrent = two; | |
let tempSum; | |
let resultList; | |
let resultCurrent; | |
while (leftCurrent || rightCurrent) { | |
if (!rightCurrent) { // Only the left digit is present | |
tempSum = leftCurrent.value + carry; | |
leftCurrent = leftCurrent.next; | |
} else if (!leftCurrent) { // Only the right digit is present | |
tempSum = rightCurrent.value + carry; | |
rightCurrent = rightCurrent.next; | |
} else { // Both the digits are present | |
tempSum = leftCurrent.value + rightCurrent.value + carry; | |
leftCurrent = leftCurrent.next; | |
rightCurrent = rightCurrent.next; | |
} | |
if (tempSum > 9) { // In case of a carry | |
carry = Math.floor(tempSum / 10); | |
tempSum = tempSum - (carry * 10); | |
} | |
if (!resultList) { // Only for the first time | |
resultCurrent = new Node(tempSum); | |
resultList = resultCurrent; | |
} else { // For successive times | |
resultCurrent.next = new Node(tempSum); | |
resultCurrent = resultCurrent.next; | |
} | |
} | |
// Add another most-significant digit in case of a carry | |
if (carry) { | |
resultCurrent.next = new Node(carry); | |
} | |
return resultList; | |
}; | |
console.log(addReverseLists(numberOne, numberTwo)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment