跳转至

2. Add Two Numbers

Leetcode Math Linked List

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.

分析

题目思路是非常直接的,因为链表代表的数字是反序的,难点在于考虑进位和链表结束的情况。由于新的节点等于链表1的节点,加上链表2的节点,加上进位,所以当链表1或者链表2加完以后,就不需要再加这个链表。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode root = new ListNode(-1);
    ListNode cur = root;
    int carry = 0;

    // 最高有效位为min(l1, l2)
    while (l1 != null || l2 != null || carry !=0) {
        int num = 0;
        if (l1 != null) {
            num = l1.val;
            l1 = l1.next;
        }
        if (l2 != null) {
            num += l2.val;
            l2 = l2.next;
        }
        num += carry;
        if (num > 9) {
            num -= 10; carry = 1;
        } else carry = 0;
        cur.next = new ListNode(num);
        cur = cur.next;
    }

    return root.next;
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0 # 处理技巧1: 使用carry
        root = ln = ListNode(0)
        while l1 or l2 or carry:
            l1val = l2val = 0  # 初始化l1val和l2val
            if l1:
                l1val = l1.val
                l1 = l1.next
            if l2:
                l2val = l2.val
                l2 = l2.next
            carry, val = divmod(l1val+l2val+carry, 10) #divmod return quotient and reminder

            ln.next = ListNode(val)
            ln  = ln.next        
        return root.next