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

[LeetCode] Add Two Numbers

时间:2014-10-05 23:28:39      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   ar   strong   sp   div   

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

 1 class Solution {
 2 public:
 3     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
 4         if(!l1&&!l2) return NULL;
 5         if(!l1||!l2) return l1?l1:l2;
 6 
 7         int overdigit = 0;
 8         ListNode *p1 = l1;
 9         ListNode *p2 = l2;
10         ListNode *phead = NULL;
11         ListNode *pbody = NULL;
12 
13         while(p1&&p2){
14             int each_digit_val = p1->val + p2->val + overdigit;
15 
16             ListNode *pnew = new ListNode(each_digit_val%10);
17             if(!phead) phead = pnew;
18 
19             if(!pbody) pbody = pnew;
20             else{
21                 pbody->next = pnew;
22                 pbody = pnew;
23             }
24 
25             if(each_digit_val>=10) overdigit = 1;
26             else overdigit = 0;
27 
28             p1 = p1->next;p2 = p2->next;
29         }
30 
31         ListNode *p3 = p1?p1:p2;
32         while(p3||overdigit==1){
33             ListNode *pnew = new ListNode(p3?((p3->val + overdigit)%10):overdigit);
34             pbody->next = pnew;
35             pbody = pnew;
36 
37             if(((p3?(p3->val):0) + overdigit)>=10) overdigit = 1;
38             else overdigit = 0;
39             p3 = p3?p3->next:NULL;
40         }
41         return phead;
42     }
43 };

[LeetCode] Add Two Numbers

标签:des   style   blog   color   io   ar   strong   sp   div   

原文地址:http://www.cnblogs.com/zhouyoulie/p/4007504.html

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