努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/add-two-numbers/description/

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        int carry = 0;
        while (l1 != null && l2 != null) {
            head.next = new ListNode((l1.val + l2.val + carry) % 10);
            carry = (l1.val + l2.val + carry) / 10;
            l1 = l1.next;
            l2 = l2.next;
            head = head.next;
        }
        while (l1 != null) {
            head.next = new ListNode((l1.val + carry) % 10); // Attn! Forgot about carry
            carry = (l1.val + carry) / 10;
            l1 = l1.next;
            head = head.next;
        }
        while (l2 != null) {
            head.next = new ListNode((l2.val + carry) % 10);
            carry = (l2.val + carry) / 10;
            l2 = l2.next;
            head = head.next;
        }
        if (carry != 0) {
            head.next = new ListNode(carry);
        }
        return dummy.next;
    }
}

 

Previously failed cases:
Failed case: forgot carry
Input:
[5]
[5]
Output:
[0]
Expected:
[0,1]

Failed case: calculate carry for the rest of the list
Input:
[1]
[9,9]
Output:
[0,10]
Expected:
[0,0,1]

Failed case: Move l1, l2 before calculating carry
Runtime Error Message:
Line 25: java.lang.NullPointerException
Last executed input:
[1,8]
[0]

Failed case: was using head.next = new ListNode((l1.val + l2.val) % 10 + carry);
Input:
[3,7]
[9,2]
Output:
[2,10]
Expected:
[2,0,1]

posted on 2017-10-25 00:33  努橙  阅读(165)  评论(0)    收藏  举报