2. Add Two Numbers

2018-06-20  本文已影响0人  JamesLivin

Problem

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

Elementary Math/基础数学

通过从链表头部开始模拟每一位数字的求和,来获得进位数值。
如同在纸上进行计算时一样,我们从最低有效位开始求和,即l1和l2的头部。由于每一位的数值范围是0到9,求和可能会溢出。此时,我们只保留个位数,将进位记为1,并且参加下一位的计算。在十进制加法中,进位只可能是0或者1。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

复杂度分析

上一篇下一篇

猜你喜欢

热点阅读