2. Add Two Numbers

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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

(1) Java

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        int carry = 0;
        ListNode dumb = new ListNode(0);
        ListNode prev = dumb;
        while (l1 != null || l2 != null) {
            int val = carry;
            if (l1 != null) {
                val += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                val += l2.val;
                l2 = l2.next;
            }
            ListNode node = new ListNode(val%10);
            prev.next = node;
            prev = node;
            carry = val/10;
        }
        if (carry != 0) {
            ListNode node = new ListNode(carry);
            prev.next = node;
        }
        return dumb.next;
    }

(2) Python

def addTwoNumbers(self, l1, l2):
        carry = 0;
        res = n = ListNode(0);
        while l1 or l2 or carry:
            if l1:
                carry += l1.val
                l1 = l1.next;
            if l2:
                carry += l2.val;
                l2 = l2.next;
            carry, val = divmod(carry, 10)
            n.next = n = ListNode(val);
        return res.next;

(3) Scala

object Solution {
    def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
        var dummyNode = new ListNode(0)
        var cur = dummyNode
        var carry = 0
        def addInternal(l1: ListNode, l2: ListNode): Unit = {
            if (l1 != null || l2 != null) {
                var a = if (l1 != null) l1.x else 0
                var b = if (l2 != null) l2.x else 0
                var sum = a + b + carry
                cur.next = new ListNode(sum % 10)
                cur = cur.next
                carry = sum / 10
                addInternal(if (l1 != null) l1.next else null, if(l2 != null) l2.next else null)
            }
        }
        addInternal(l1, l2)
        if (carry > 0) {
            cur.next = new ListNode(carry)
        }
        dummyNode.next
    }
}

results matching ""

    No results matching ""