kyle4real
kyle4real

Reputation: 86

Adding Two Numbers From Linked List JavaScript

Given two non-empty linked-lists representing two non-negative integers (in reverse order), add the two numbers and return the sum as a linked list.

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Everything works properly on my end, but there's a runtime error on leetcode and I can't quite figure out why. Here's my code:

const l1 = [2,4,3]
const l2 = [5,6,4]

const addTwoNumbers = (l1, l2) => {
    l1 = reverseLinkedList(l1)
    l2 = reverseLinkedList(l2)
    const l1sum = linkedListNum(l1)
    const l2sum = linkedListNum(l2)
    let sum = l1sum + l2sum
    // for 0 sum
    if (!sum) return [sum]
    const l3 = [];
    while (sum > 0) {
        l3.push(sum % 10);
        sum /= 10;
        sum = Math.trunc(sum)
    }
    return l3
}

const reverseLinkedList = (ll) => {
    let rev = []
    for (let i = ll.length - 1; i >= 0; i--) {
        rev.push(ll[i])
    }
    return rev
}

const linkedListNum = (ll) => {
    let sum
    for (let i = 0; i < ll.length; i++) {
        if (!i) {
            sum = ll[i]
            continue
        }
        sum *= 10
        sum += ll[i]
    }
    return sum
}

const answer = addTwoNumbers(l1,l2)
console.log(answer);
// answer output: [7,0,8]

Here's the error:

Line 65 in solution.js
             throw new TypeError(__serialize__(ret) + " is not valid value for thereturn type ListNode")
             ^
TypeError: [null] is not valid value for the expected return type ListNode
    Line 65: Char 20 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in rumner.is (Object.runner)
    Line 49: Char 26 in solution.js (Object.<anonymous>)
    Line 1251: Char 30 in loader.js (Module._compile)
    Line 1272: Char 10 in loader.js (Object.Module._extensions..is)
    Line 1100: Char 32 in loader.is (Module.load)
    Line 962: Char 14 in loader.js (Function.Module._load)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    Line 17: Char 47 in run_main_module.js

Unrelated: This is my first question asked on stack overflow, let me know how I did.

Upvotes: 0

Views: 690

Answers (3)

h-sifat
h-sifat

Reputation: 1595

Why don't you just use already available methods in javascript?

Here's my solution:

const l1 = [2,4,3];
const l2 = [5,6,4];
  
function getNum(list) {
    const numStr = list
    .reverse()
    .join("");
    return Number(numStr);
  }
  
function getList(num) {
    return num
    .toString()
    .split("")
    .reverse()
    .map(Number);
  }
  
  const sum = getNum(l1) + getNum(l2);
  const result = getList(sum)
  console.log(result)

Or if you want to do it in a mathematical way:

const l1 = [2,4,3];
const l2 = [5,6,4];

function getNum(list) {
  return list
    .reduce((a, c, i) => a + c * (10 ** i));
}
  
function getList(num) {
  const list = []
  while(num !=0) {
    list.push(num % 10);
    num = Math.floor(num / 10)
  }
  return list;
}

const sum = getNum(l1) + getNum(l2);
const result = getList(sum)
console.log(result)

Upvotes: 3

deepakchethan
deepakchethan

Reputation: 5600

if (!sum) return [sum] is the issue here. when the inputs are empty array like as seen in the snippet. The sum would be null and is causing this issue. You can fix this by initialising the sum in linkedListNum to 0. That way it will return [0] instead.

const l1 = []
const l2 = []

const addTwoNumbers = (l1, l2) => {
    l1 = reverseLinkedList(l1)
    l2 = reverseLinkedList(l2)
    const l1sum = linkedListNum(l1)
    const l2sum = linkedListNum(l2)
    let sum = l1sum + l2sum
    // for 0 sum
    if (!sum) return [sum] // here is the issue
    const l3 = [];
    while (sum > 0) {
        l3.push(sum % 10);
        sum /= 10;
        sum = Math.trunc(sum)
    }
    return l3
}

const reverseLinkedList = (ll) => {
    let rev = []
    for (let i = ll.length - 1; i >= 0; i--) {
        rev.push(ll[i])
    }
    return rev
}

const linkedListNum = (ll) => {
    let sum = 0; // initialize sum here
    for (let i = 0; i < ll.length; i++) {
        if (!i) {
            sum = ll[i]
            continue
        }
        sum *= 10
        sum += ll[i]
    }
    return sum
}

const answer = addTwoNumbers(l1,l2)
console.log(answer);

Upvotes: 2

Andy
Andy

Reputation: 63524

There are far easier methods of achieving this by using modern array methods.

  1. Create a number from each array

  2. Add them together

  3. Coerce that back to a string, reverse it, and map the elements back to numbers.

const a1 = [2,4,3];
const a2 = [5,6,4];

// Take an array, reverse it, join it up into a string
// again and make it a number
const getNumber = arr => Number(arr.reverse().join(''));

// Sum the numbers from each array
const getSum = (arr1, arr2) => getNumber(arr1) + getNumber(arr2);

// Coerce the number to a string, split it into an array
// and reverse it, and map the strings back to numbers
const getResult = sum => sum.toString().split('').reverse().map(Number);    

// Get the result
console.log(getResult(getSum(a1, a2)));

Upvotes: 4

Related Questions