1. 程式人生 > >【leetcode】2-Add Two Numbers

【leetcode】2-Add Two Numbers

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.
/**
 * 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 temp = new ListNode(-1);
        ListNode res = temp;
        int jw = 0;
        while(l1!=null || l2!=null){
            int d1 = l1 == null ? 0 : l1.val;
            int d2 = l2 == null ? 0 : l2.val;
            int sum = d1 + d2 + jw;
            jw = sum >= 10 ? 1 : 0;
            temp.next = new ListNode(sum % 10);
            temp = temp.next;
            if(l1!=null) l1 = l1.next;
            if(l2!=null) l2 = l2.next;
        }
        if(jw == 1){
            temp.next = new ListNode(1);
        }
        
        return res.next;
    }
}

* 連結串列題目要設定一個提前點,然後一個新點用來返回結果 * 這道題一開始沒設定提前點,結果最後又new了一個廢點,所以用最後判斷非null的話都向後挪一位變成都是null,所以跳出迴圈結束,就不再new新的temp點 * 題目最後加特殊判斷來看是否需要進位,因為這已經跳出while迴圈了