LeetCode——Add Two Numbers

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

题目大意,给两个链表,一个结点存一位数,逆序存储,任务是把两个数加起来,逆序输出。返回类型为链表。

e.g. (2 -> 4 -> 3) + (5 -> 6 -> 4)

就是342+465=807,逆序存到链表里就是 7 -> 0 -> 8,返回就可以了。

下面是对Node的定义。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

一开始,想着so easy的,把两个数读进来,加起来=sum,然后sum mod 10存起来,sum/=10。。。结果TLE。。。真是匪夷所思的TLE

然后就换了一种方式实现,读一个数处理一个数,AC了,今天再打开这个题还是觉得匪夷所思,又提交了一次之前的代码,通过分析给出的错误信息,发现应该是溢出了,把sum改成long类型的就可以了。。。但其实虽然long可以了,如果系统测试数据更硬一点的话,还是过不了的,或者再把long改成BigInteger。。。所以推荐addTwoNumbers_New方法里的实现方式。

 1 public ListNode addTwoNumbers_New(ListNode l1, ListNode l2) {
 2         ListNode res = new ListNode(0);
 3         ListNode cur = res;
 4         int sum = 0;
 5         while (l1 != null || l2 != null) {
 6             sum /= 10;
 7             if (l1 != null) {
 8                 sum += l1.val;
 9                 l1 = l1.next;
10             }
11             if (l2 != null) {
12                 sum += l2.val;
13                 l2 = l2.next;
14             }
15             cur.next = new ListNode(sum % 10);
16             cur = cur.next;
17         }
18         if (sum / 10 == 1)
19             cur.next = new ListNode(1);
20         return res.next;
21     }
22 
23     public ListNode addTwoNumbers_Deprecated(ListNode l1, ListNode l2) {
24         ListNode res = new ListNode(0);
25         ListNode cur = res;
26         long sum = 0;
27         int p = 0;
28         while (l1 != null) {
29             sum += l1.val * Math.pow(10, p++);
30             l1 = l1.next;
31         }
32         p = 0;
33         while (l2 != null) {
34             sum += l2.val * Math.pow(10, p++);
35             l2 = l2.next;
36         }
37         if (sum == 0)
38             return res;
39         while (sum != 0) {
40             ListNode node = new ListNode((int) (sum % 10));
41             node.next = cur.next;
42             cur.next = node;
43             cur = node;
44             sum /= 10;
45         }
46         return res.next;
47     }

 

posted @ 2014-04-29 10:51  丶Blank  阅读(188)  评论(0编辑  收藏  举报