Skip to content

Instantly share code, notes, and snippets.

@wataruoguchi
Last active July 28, 2019 05:37
Show Gist options
  • Save wataruoguchi/ede089263f7b9dfe9357dedda1a7ea2f to your computer and use it in GitHub Desktop.
Save wataruoguchi/ede089263f7b9dfe9357dedda1a7ea2f to your computer and use it in GitHub Desktop.
Add Two Numbers Represented by Linked Lists
// https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists-set-3/
// Same - https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/
function printList(root) {
let tmp = root;
let arr = [];
while (tmp) {
arr.push(tmp.val);
tmp = tmp.next;
}
return arr;
}
class Node {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
function getIntFromList(list) {
const listArr = printList(list);
return listArr.reduce((acc, num, idx) => {
return acc + num * Math.pow(10, listArr.length - 1 - idx);
}, 0);
}
function addNumbers(L1, L2) {
const intL1 = getIntFromList(L1);
const intL2 = getIntFromList(L2);
return intL1 + intL2;
}
// https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists-set-3/
// Same - https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/
const ex1L1 = new Node(5, new Node(6, new Node(3)));
const ex1L2 = new Node(8, new Node(4, new Node(2)));
console.log(addNumbers(ex1L1, ex1L2) === 1405);
const ex2L1 = new Node(1, new Node(0, new Node(0)));
const ex2L2 = new Node(9, new Node(1));
console.log(addNumbers(ex2L1, ex2L2) === 191);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment