1. 程式人生 > >[leetcode]2. Add Two Numbers兩數相加

[leetcode]2. Add Two Numbers兩數相加

表示 generate repr onu ner plan store width where

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.

  

題目:

用兩個鏈表表示的兩個數,求相加之和

Solution1: For given two lists, keep looping where either one isn‘t null. When ListNode comes to null, consider its val as 0.

For result list, use a dummy node.

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

code:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 /*
10  Time Complexity:  O(max(l1,l2))
11  Space Complexity: O(max(l1,l2)) 
12
*/ 13 class Solution { 14 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 15 ListNode dummy = new ListNode(-1); 16 ListNode pre = dummy; 17 ListNode p1 = l1; 18 ListNode p2 = l2; 19 int carry = 0; 20 while(p1 != null || p2 != null){ 21 int x = (p1 != null) ? p1.val : 0; 22 int y = (p2 != null) ? p2.val : 0; 23 int sum = carry + x + y; 24 carry = sum / 10; 25 // generate the result list 26 pre.next = new ListNode(sum % 10); 27 // move three lists pointers 28 pre = pre.next; 29 if(p1 != null) p1 = p1.next; 30 if(p2 != null) p2 = p2.next; 31 } 32 // in case last two digit sum > 10 33 if(carry > 0){ 34 pre.next = new ListNode(carry); 35 } 36 return dummy.next; 37 } 38 }

[leetcode]2. Add Two Numbers兩數相加