码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode : add two numbers

时间:2014-07-29 10:53:06      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   2014   for   

bubuko.com,布布扣

解法:比较简单,用plus表示进位

bubuko.com,布布扣
 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 *result=NULL;
13         ListNode *p=NULL;
14         int plus=0;
15 
16         while(l1!=NULL && l2!=NULL)
17         {
18             int tmp=l1->val+l2->val+plus;
19             plus=tmp/10;
20 
21             if(result == NULL)
22             {
23                 result = new ListNode(tmp%10);
24                 p = result;
25             }
26             else
27             {
28                 p->next = new ListNode(tmp%10);
29                 p = p->next;
30             }
31             l1=l1->next;
32             l2=l2->next;
33         }
34         
35 
36         while(l1!=NULL)
37         {
38             int tmp = l1->val + plus;
39             plus = tmp/10;
40 
41             if(result == NULL)
42             {
43                 result = new ListNode(tmp%10);
44                 p = result;
45             }
46             else
47             {
48                 p->next=new ListNode(tmp%10);
49                 p=p->next;
50             }
51             l1=l1->next;
52         }
53 
54         while(l2!=NULL)
55         {
56             int tmp = l2->val + plus;
57             plus = tmp/10;
58 
59             if(result == NULL)
60             {
61                 result = new ListNode(tmp%10);
62                 p = result;
63             }
64             else
65             {
66                 p->next=new ListNode(tmp%10);
67                 p=p->next;
68             }
69             l2=l2->next;
70         }
71 
72         if(plus!=0)
73         {
74             p->next=new ListNode(plus);
75         }
76 
77         return result;
78     }
79 };
View Code

 

LeetCode : add two numbers,布布扣,bubuko.com

LeetCode : add two numbers

标签:style   blog   http   color   os   io   2014   for   

原文地址:http://www.cnblogs.com/crystal-miao/p/3873883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!