aiheshan

有多自律,才能有多自由

导航

leetcode 2. Add Two Numbers

https://leetcode.com/problems/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

思路:方法比较简单,直接将每个节点的值相加取10的余数,然后除10为进位。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12         ListNode *t1 = l1;
13         ListNode *t2 = l2;
14         int k=0;
15         int a1,a2,t=0;
16         ListNode *pre =NULL;
17         ListNode *result = NULL;
18         while(t1&&t2) {
19              a1=t1->val;t1=t1->next;
20              a2=t2->val;t2=t2->next;
21              ListNode *temp = new ListNode((a1+a2+t)%10);
22              t = (a1+a2+t)/10;
23              if(pre) pre->next = temp;
24              else result = temp;
25              pre=temp;
26         }
27         while(t1){
28             int a = t1->val;t1=t1->next;
29             ListNode *temp = new ListNode((a+t)%10);
30             t = (a+t)/10;
31             if(pre) pre->next = temp;
32             else result = temp;
33             pre = temp;
34         }
35          while(t2){
36             int a = t2->val;t2=t2->next;
37             ListNode *temp = new ListNode((a+t)%10);
38             t = (a+t)/10;
39            if(pre) pre->next = temp;
40            else result = temp;
41             pre = temp;
42         }
43         if(t) {
44             ListNode *temp = new ListNode(t);
45             pre->next = temp;
46         }
47         return result;
48     }
49     
50 };

在leetcode上时间为36ms。

 

posted on 2016-07-22 15:20  aiheshan  阅读(135)  评论(0编辑  收藏  举报