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

LeetCode – Refresh – Add Two Numbers

时间:2015-03-18 07:47:51      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Same with add binary. You can also skip delete the result pointer. But just return result->next. Depends on the interviewer.

 

 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         if (!l1) return l2;
13         if (!l2) return l1;
14         ListNode *result = new ListNode(0);
15         ListNode *runner = result;
16         int carry = 0, sum = 0;
17         while (l1 || l2) {
18             sum = carry;
19             if (l1) {
20                 sum += l1->val;
21                 l1 = l1->next;
22             }
23             if (l2) {
24                 sum += l2->val;
25                 l2 = l2->next;
26             }
27             carry = sum/10;
28             runner->next = new ListNode(sum%10);
29             runner = runner->next;
30         }
31         if (carry) {
32             runner->next = new ListNode(carry);
33         }
34         runner = result->next;
35         delete result;
36         return runner;
37     }
38 };

 

LeetCode – Refresh – Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346157.html

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