Sunday, May 1, 2016

[LintCode] 167 Add Two Numbers 解题报告

Description
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.


Example
Given 7->1->6 + 5->9->2. That is, 617 + 295.
Return 2->1->9. That is 912.
Given 3->1->5 and 5->9->2, return 8->0->8.


思路
一位一位比。注意carry > 0的情况需要在循环里做,否则会漏掉进位到第一位的数字。


Code
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;      
 *     }
 * }
 */
public class Solution {
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    public ListNode addLists(ListNode l1, ListNode l2) {
        // write your code here
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry > 0) {
            int aa = l1 == null ? 0 : l1.val;
            if (l1 != null) {
                l1 = l1.next;
            }
            int bb = l2 == null ? 0 : l2.val;
            if (l2 != null) {
                l2 = l2.next;
            }
            curr.next = new ListNode((aa + bb + carry) % 10);
            curr = curr.next;
            carry = aa + bb + carry > 9 ? 1 : 0;
        }
        return dummy.next;
    }
}