Reputation: 5657
In this question: https://leetcode.com/problems/add-two-numbers/description/, I've figured out how to get sum of the digits (i.e. 807), but now I need to convert that number into a linked list (e.g. 7 -> 0 -> 8).
How do I create a linkedlist from a number?
Class function for creating a list node:
function ListNode(val) {
this.val = val;
this.next = null;
}
Rest of my code:
var addTwoNumbers = function(l1, l2) {
function findVal(linkedList) {
return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);
}
var l1num = parseInt(findVal(l1).split('').reverse().join(''));
var l2num = parseInt(findVal(l2).split('').reverse().join(''));
var sum = l1num + l2num;
// Create linked list from sum
Upvotes: 0
Views: 1463
Reputation: 18281
If you turn your number into an array, you can then use the array.prototype.reduce
function.
let number = 807;
function ListNode(val) {
this.val = val;
this.next = null;
}
// Convert the number into a string and split that into an array of digits
let arr = Array.from(number.toString());
// Iterate through the elements, and create the nodes
let head = arr.reduce((nextNode, curr) => {
let node = new ListNode(curr);
node.next = nextNode;
return node;
}, null);
// Print out the values
let node = head;
while(node) {
console.log(node.val);
node = node.next
}
Upvotes: 3
Reputation: 22876
Easier with recursion:
f = n => n ? { val: n % 10, next: f(n / 10 | 0) } : null
console.log( f(807) )
f = (a, b, c = 0) => a && b && { val: (c += a.val + b.val) % 10,
next: f(a.next, b.next, c > 9) } || null
console.log( f( { val: 2, next: { val: 4, next: { val: 3 } } },
{ val: 5, next: { val: 6, next: { val: 4 } } } ) )
Upvotes: 1