Home > Software design >  "Add Two Numbers" JavaScript Leetcode error
"Add Two Numbers" JavaScript Leetcode error

Time:11-10

I am getting errors in my leetcode and I am not sure why:

var addTwoNumbers = function(l1, l2) {
let newL1 = []
let newL2 = []
let answer = []

for(let i = 0; i < l1.length; i  ) {
    newL1[i] = l1[l1.length - 1 - i]
}

for(let i = 0; i < l2.length; i  ) {
    newL2[i] = l2[l2.length - 1 - i]
}

let num = parseInt(newL1.toString().replace(/,/g, ''))   parseInt(newL2.toString().replace(/,/g, ''))

let rawAnswer = (num.toString().split(""))

for(let i=0; i < rawAnswer.length; i  ) {
    answer[i] = parseInt(rawAnswer[i])
}

return answer

}

Error:

Line 45 in solution.js
             throw new TypeError(__serialize__(ret)   " is not valid value for the expected return type ListNode");
             ^
TypeError: null is not valid value for the expected return type ListNode
    Line 45: Char 20 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in runner.js (Object.runner)
    Line 29: 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..js)
    Line 1100: Char 32 in loader.js (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

Challenge Description:

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 contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

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

I am not sure why I am getting this error, but I know I am doing something that leetcode doesn't like.

Thanks

CodePudding user response:

The description reads: return the sum as a linked list

You're doing two parseInt and returning the sum (that is a number) but it should return a linked list instead, defined by the head of the list (the first ListNode object.

  • Related