Add Two Numbers — LeetCode #2

Add Two Numbers — LeetCode #2

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 1:

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

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].

  • 0 <= Node.val <= 9

  • It is guaranteed that the list represents a number that does not have leading zeros.

Solutions:

Python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
    dummy = current = ListNode(0)
    carry = 0

    while l1 or l2 or carry:
        if l1:
            carry += l1.val
            l1 = l1.next
        if l2:
            carry += l2.val
            l2 = l2.next
        current.next = ListNode(carry % 10)
        current = current.next
        carry //= 10

    return dummy.next

This function starts with two pointers l1 and l2 pointing to the head nodes of the two linked lists, and a carry variable initialized to 0. It then enters a loop that continues until both l1 and l2 are None and the carry is 0.

Inside the loop, the function adds the values of the current nodes l1 and l2 (if they exist) to the carry variable. It then creates a new node with the value carry % 10 and appends it to the result linked list. The carry variable is updated to carry // 10, which is the carry for the next iteration.

Finally, the function returns the next node of the dummy head node, which is the first node of the result linked list.

C#:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        var dummy = new ListNode(0);
        var current = dummy;
        var carry = 0;

        while (l1 != null || l2 != null || carry != 0)
        {
            if (l1 != null)
            {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null)
            {
                carry += l2.val;
                l2 = l2.next;
            }
            current.next = new ListNode(carry % 10);
            current = current.next;
            carry /= 10;
        }

        return dummy.next;
    }
}

This function is similar to the Python version, with the main difference being the syntax for creating a new object (using the new keyword in C#) and the way integer division is performed (using the / operator in C#).

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        int carry = 0;

        while (l1 != null || l2 != null || carry != 0) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            current.next = new ListNode(carry % 10);
            current = current.next;
            carry /= 10;
        }

        return dummy.next;
    }
}

This function is similar to the Python version, with the main difference being the syntax for creating a new object (using the new keyword in Java) and the way integer division is performed (using the / operator in Java).

Javascript:

/**
 * 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 dummy = new ListNode(0);
    let current = dummy;
    let carry = 0;

    while (l1 || l2 || carry) {
        if (l1) {
        carry += l1.val;
        l1 = l1.next;
        }
        if (l2) {
        carry += l2.val;
        l2 = l2.next;
        }
        current.next = new ListNode(carry % 10);
        current = current.next;
        carry = Math.floor(carry / 10);
    }

    return dummy.next;
};

This function is similar to the Python version, with the main difference being the syntax for creating a new object (using the new keyword in JavaScript) and the way integer division is performed (using the Math.floor function in JavaScript).

Typescript:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let dummy = new ListNode(0);
    let current = dummy;
    let carry = 0;

    while (l1 || l2 || carry) {
        if (l1) {
        carry += l1.val;
        l1 = l1.next;
        }
        if (l2) {
        carry += l2.val;
        l2 = l2.next;
        }
        current.next = new ListNode(carry % 10);
        current = current.next;
        carry = Math.floor(carry / 10);
    }

    return dummy.next;
};

PHP:

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {

    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function addTwoNumbers($l1, $l2) {
        $dummy = new ListNode(0);
        $current = $dummy;
        $carry = 0;

        while ($l1 || $l2 || $carry) {
            if ($l1) {
                $carry += $l1->val;
                $l1 = $l1->next;
            }
            if ($l2) {
                $carry += $l2->val;
                $l2 = $l2->next;
            }
            $current->next = new ListNode($carry % 10);
            $current = $current->next;
            $carry = (int)($carry / 10);
        }

        return $dummy->next;
    }
}

This function is similar to the Python version, with the main difference being the syntax for creating a new object (using the new keyword in PHP) and the way integer division is performed (using the (int) casting operator in PHP).

To have more solutions to LeetCode problems just visit my article here on medium https://medium.com/@araneznorman

Did you find this article valuable?

Support Norman Aranez by becoming a sponsor. Any amount is appreciated!