2.Add Two Numbers

題目連接:https://leetcode.com/problems/add-two-numbers/description/ide

題目大意:給出兩個單鏈表,表示兩個數字,這兩個數字中的每一位上的數字在單鏈表中都倒序存放,每一個結點中都含有一個非負整數,計算這兩個數字的和,要求倒序插入到單鏈表中並返回。例子以下:spa

法一(WA):利用棧,對於每個鏈表,將數字取出來依次放入棧中,而後再取出存成它原本表示的數,而後將兩個數相加,再將相加的結果存放進單鏈表中返回。這個解法比較好理解,就是轉換成數學數字再計算,可是當數字長度超過int範圍的時候就會發生問題,也就是int會存不下的問題。代碼以下:code

 1     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         Stack<Integer> stack1 = new Stack<Integer>();
 3         Stack<Integer> stack2 = new Stack<Integer>();
 4         while(l1 != null) {
 5             stack1.push(l1.val);
 6             l1 = l1.next;
 7         }
 8         while(l2 != null) {
 9             stack2.push(l2.val);
10             l2 = l2.next;
11         }
12         int num1 = 0, num2 = 0;
13         while(!stack1.isEmpty()) {
14             num1 = num1 * 10 + stack1.pop();
15         }
16         while(!stack2.isEmpty()) {
17             num2 = num2 * 10 + stack2.pop();
18         }
19         int num = num1 + num2;
20         ListNode l = new ListNode(num % 10);
21         num = num / 10;
22         ListNode tmp = null, p = l;
23         while(num != 0) {
24             tmp = new ListNode(num % 10);
25             tmp.next = null;
26             p.next = tmp;
27             p = tmp;
28             num = num / 10;
29         }
30         return l;
31     }
View Code

法二:在經歷上個方法的失敗後,立馬想到了大數加法,轉而用大數加法順利成章的作,迎刃而解,只是要處理一些細節問題,好比要考慮到最後flag不是0而是1的問題。代碼以下(耗時55ms):blog

 1     //相似大數加法
 2     public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
 3         ListNode l = null, tmp = null, p = null;
 4         int flag = 0, num = 0;
 5         while(l1 != null && l2 != null) {
 6             if(l == null) {
 7                 num = l1.val + l2.val;
 8                 flag = num / 10;
 9                 l = new ListNode(num % 10);
10                 l.next = null;
11                 p = l;
12             }
13             else {
14                 num = l1.val + l2.val + flag;
15                 flag = num / 10;
16                 tmp = new ListNode(num % 10);
17                 tmp.next = null;
18                 p.next = tmp;
19                 p = tmp;
20             }
21             l1 = l1.next;
22             l2 = l2.next;
23         }
24         while(l1 != null) {
25             num = flag + l1.val;
26             flag = num / 10;
27             tmp = new ListNode(num % 10);
28             tmp.next = null;
29             p.next = tmp;
30             p = tmp;
31             l1 = l1.next;
32         }
33         while(l2 != null) {
34             num = flag + l2.val;
35             flag = num / 10;
36             tmp = new ListNode(num % 10);
37             tmp.next = null;
38             p.next = tmp;
39             p = tmp;
40             l2 = l2.next;
41         }
42         if(flag != 0) {
43             tmp = new ListNode(flag);
44             tmp.next = null;
45             p.next = tmp;
46             p = tmp;
47         }
48         return l;
49     }
View Code
相關文章
相關標籤/搜索