Add Two Numbers [JavaScript]


  • 0
    R

    Hello, guys!
    I am trying to solve the second task using JavaScript, but a couple of test cases I just can't pass.
    Here you go, my code:

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function (l1, l2) {
        var number1 = getNumber(l1);
        var number2 = getNumber(l2);
        var sum = number1 + number2;
        var list, temp;
        var numberCount = getNumberCount(sum);
    
        if (sum !== 0) {
            while (numberCount--) {
                if (list) {
                    temp = list;
                }
    
                list = new ListNode(parseInt((sum / pow(10, numberCount))) % 10);
                list.next = temp;
            }
        }
        else {
            list = new ListNode(sum);
        }
    
        return list;
    };
    
    function pow(x, y) {
        if (y === 0) {
            return 1;
        }
        else {
            var p = 1;
            for (var i = 1; i <= y; i++) {
                p = p * x;
            }
            return p;
        }
    }
    
    function getNumber(array) {
        var number = 0;
        var i = 0;
    
        while (array !== null && array.val !== null) {
            number = number + array.val * pow(10, i);
            array = array.next;
            i++;
        }
    
        return number;
    }
    
    var getNumberCount = function (number) {
        var i = 0;
        while (number > 0) {
            number = number / 10;
            i++;
        }
        return i;
    };
    

    For now, I cannot handle the following input:

    [2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9]
    [5,6,4,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9,9,9,9]
    

    Because I encountered scientific number and now I have to rewrite the method getNumberCount().
    Could you provide any ideas, how can I fit the fix into my current solution?

    Thanks a lot!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.