JavaScript O(n) time and O(n) space using Add Strings


  • 0
    var addTwoNumbers = function(l1, l2) {
        return num2list(add(list2num(l1), list2num(l2)));
    };
    
    function list2num(list) {
        let node = list;
        let res = '';
        while (node) {
            res += node.val;
            node = node.next;
        }
        return res;
    }
    
    function num2list(num) {
        let head = null;
        const arr = num.split('');
        while (arr.length) {
            let node = new ListNode(parseInt(arr.pop()));
            node.next = head;
            head = node;
        }
        return head;
    }
    
    function add(num1, num2) {
        let sum = '';
        let carry = false;
        let i = num1.length - 1;
        let j = num2.length - 1;
        while (i >= 0 || j >= 0) {
            let column = (1 * carry) + (i >= 0 ? parseInt(num1[i]) : 0) + (j >= 0 ? parseInt(num2[j]) : 0);
            i--;
            j--;
            if ((i >= 0 || j >= 0) && column >= 10) {
                column -= 10;
                carry = true;
            } else {
                carry = false;
            }
            sum = column + sum;
        }
        return sum;
    }
    

    Reuse our solution to Add Strings for the add function here.


Log in to reply
 

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