1. 程式人生 > >LeetCode 2.Add Two Numbers

LeetCode 2.Add Two Numbers

elf output git any == != ret ber spa

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.

思路:鏈表合並與實現加法運算的結合版。有三種情況:
1.兩個鏈表都不為空同時判斷是否有進位,設置標誌位,取余,處除10
2.一個鏈表為空另一個不為空同時判斷是否有進位,若有進位與1判斷相同,若無進位直接將鏈接追加到新鏈表尾部。
3.兩個鏈表都為空同時判斷是否有進位,有進位在尾部追加1。
 1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
2 ListNode head = null; 3 ListNode rear = null; 4 int flag = 0; 5 ListNode node = null; 6 while(l1!=null&&l2!=null) {//處理兩個鏈表對應位置都不為0的情況 7 if(flag==1) {//是否進位 8 node = new ListNode((l1.val+l2.val+1)%10); 9 }else
{ 10 node = new ListNode((l1.val+l2.val)%10); 11 }//進位 12 flag = (l1.val+l2.val+flag)/10; 13 if(head==null) {//頭節點為空 14 head = node; 15 rear = head; 16 }else { 17 rear.next = node; 18 rear = rear.next; 19 } 20 l1 = l1.next; 21 l2 = l2.next; 22 } 23 //有進位需要進行特殊處理。比如5+5=10,1+99=100。 24 while(flag==1) {//有一個鏈表對應位置為空,同時有進位 25 if(l1==null&&l2==null) { 26 node = new ListNode(1); 27 flag = 0; 28 } 29 else { 30 if(l1!=null) { 31 node = new ListNode((l1.val+1)%10); 32 flag = (l1.val+1)/10; 33 l1 = l1.next; 34 } 35 if(l2!=null) { 36 node = new ListNode((l2.val+1)%10); 37 flag = (l2.val+1)/10; 38 l2 = l2.next; 39 } 40 } 41 rear.next = node; 42 rear = rear.next; 43 } 44 //無進位,只需要把l1或l2剩下的節點追加到新鏈表中 45 while(l1!=null) { 46 rear.next = l1; 47 rear = rear.next; 48 l1 = l1.next; 49 } 50 while(l2!=null) { 51 rear.next = l2; 52 rear = rear.next; 53 l2 = l2.next; 54 } 55 return head; 56 57 }

LeetCode 2.Add Two Numbers