Skip to content

Latest commit

 

History

History
132 lines (105 loc) · 3.22 KB

2. Add Two Numbers.md

File metadata and controls

132 lines (105 loc) · 3.22 KB
title toc date tags top
2. Add Two Numbers
false
2017-10-10
Leetcode
Math
Linked List
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 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,更新后面的链表。

ListNode root = new ListNode(-1);
ListNode cur = root;
int carry = 0;

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

//carry != 0
ListNode prev = cur;
cur = cur.next;
while (cur != null && carry != 0) {
    int num = cur.val + carry;
    if (num > 9) {
        num -= 10; carry = 1;
    } else carry = 0;
    cur.val = num;
    prev = cur;
    cur = cur.next;
}
if (carry == 1) prev.next = new ListNode(1);


return root.next;

另一种方法是始终生成新的链表节点。由于新的节点等于链表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;
}

Python

与Java的方法2相同。

# 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