1. 程式人生 > 其它 >No.002 Add Two Numbers

No.002 Add Two Numbers

Add Two Numbers

  • Total Accepted: 160702
  • Total Submissions: 664770
  • Difficulty: Medium

  You are given two linked lists representing two non-negative numbers. 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.

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

  本題的思路其實很簡單,兩個連結串列的結構都是從低位到高位的順序,稅後要求返回的連結串列也是這樣的結構。所以我們只需要依次迴圈兩個連結串列,將對應位的數相加,並判斷是否有進位,有進位則將進位累加到下一位即可。

 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 public class Num2 {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         if(l1 == null){
12             return l2 ;
13         }
14         if(l2 == null){
15             return l1 ;
16         }
17         int nextBit = (l1.val + l2.val)/10  ;
18         int curBit = (l1.val + l2.val)%10 ;
19         ListNode head = new ListNode(curBit) ;
20         ListNode temp = head ;
21         l1 = l1.next ;
22         l2 = l2.next ;
23         //當l1、l2對應位均存在時,進行計算
24         while(l1 != null && l2 != null){
25             curBit = (l1.val + l2.val + nextBit) % 10 ;
26             nextBit = (l1.val + l2.val + nextBit)/10 ;
27             ListNode node = new ListNode(curBit) ;
28             temp.next = node ;
29             temp = temp.next ;
30             l1 = l1.next ;
31             l2 = l2.next ;
32         }
33         //判斷l1是否結束,沒有結束繼續
34         while(l1 != null){
35             curBit = (l1.val + nextBit) % 10 ;
36             nextBit = (l1.val + nextBit)/10 ;
37             ListNode node = new ListNode(curBit) ;
38             temp.next = node ;
39             temp = temp.next ;
40             l1 = l1.next ;
41         }
42         //判斷l2是否結束,沒有結束繼續
43         while(l2 != null){
44             curBit = (l2.val + nextBit) % 10 ;
45             nextBit = (l2.val + nextBit)/10 ;
46             ListNode node = new ListNode(curBit) ;
47             temp.next = node ;
48             temp = temp.next ;
49             l2 = l2.next ;
50         }
51         //判斷最後的進位位是否為0 ,不為0則需要儲存下一位
52         if(nextBit != 0){
53             ListNode node = new ListNode(nextBit) ;
54             temp.next = node ;
55         }
56         return head ;        
57     }
60 }