Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 1.23 KB

0002. Add Two Numbers.md

File metadata and controls

45 lines (39 loc) · 1.23 KB

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.

Screen Shot 2021-10-27 at 12 01 24 AM

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let head = new ListNode();
    let curr = head;
    let sum = 0;
    
    while(l1 || l2) {
        if(l1) {
            sum += l1.val;
            l1 = l1.next;
        }
        if(l2) {
            sum += l2.val;
            l2 = l2.next;
        }
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        sum = sum > 9 ? 1 : 0;
    }
    if(sum) {
        curr.next = new ListNode(sum);
    }
    return head.next
};