<pre>
You are given two non-empty 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
</pre>
JavaScript
function ListNode(val) {
this.val = val;
this.next = null;
}
const l0 = new ListNode(2);
l0.next = new ListNode(4);
l0.next.next = new ListNode(3);
const l1 = new ListNode(5);
l1.next = new ListNode(6);
l1.next.next = new ListNode(4);
var addTwoNumbers = function(l1, l2) {
l0Arr = convertListToArray(l1);
l1Arr = convertListToArray(l2);
function convertListToArray(list) {
const result = [];
let head = list;
result.push(head.val);
while (head.next !== null) {
head = head.next;
result.push(head.val);
}
return result;
}
function getReverseInt(listArr) {
let sum = 0;
let counter = 0;
for (let i = listArr.length - 1; i >= 0; i--) {
sum += listArr[i] * (10**(counter));
counter++;
}
return sum;
}
function convertIntToLinkedList(int) {
const stringInt = String(int);
const reverseStrings = stringInt.split('').reverse();
console.log(reverseStrings);
let head = new ListNode(parseInt(reverseStrings[0]));
let root = head.next;
for (let i = 1; i < reverseStrings.length; i++) {
// TODO: fix this, looks like reference issue
let current = root;
let newNode = new ListNode(parseInt(reverseStrings[i]));
current = newNode;
current = current.next;
}
return head;
}
const finalSum = getReverseInt(l0Arr) + getReverseInt(l1Arr);
return convertIntToLinkedList(finalSum);
};
console.log(addTwoNumbers(l0, l1))
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.