# leetcode2. 两数相加

### 题目描述

输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)



### code

• 直接版
/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res = new ListNode(0), *p = res;
int c=0;//进位
int sum=0;//和
while(l1&&l2){
sum = (l1->val+l2->val+c)%10;
c = (l1->val+l2->val+c)/10;
ListNode* next = new ListNode(sum);
p->next = next;
p = p->next;
l1=l1->next;
l2=l2->next;
}
while(l1){
sum = (l1->val+c)%10;
c = (l1->val+c)/10;
ListNode* next = new ListNode(sum);
p->next = next;
p = p->next;
l1=l1->next;
}
while(l2){
sum = (l2->val+c)%10;
c = (l2->val+c)/10;
ListNode* next = new ListNode(sum);
p->next = next;
p = p->next;
l2=l2->next;
}
if(c!=0){
ListNode* next = new ListNode(1);
p->next = next;
}
return res->next;
}
};

• 简洁版
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res = new ListNode(0), *p = res;
int c=0;//进位
int sum=0;//和
while(l1||l2||c){
int val1 = l1==NULL ? 0 : l1->val;
int val2 = l2==NULL ? 0 : l2->val;
sum = val1+val2+c;
c = sum/10;

ListNode* next = new ListNode(sum%10);
p->next = next;
p = p->next;

if(l1)
l1 = l1->next;
if(l2)
l2 = l2->next;
}
return res->next;
}
};


### 测试数据

[0] ； [0][0]
[]；[][]
[9,9,9]；[2,4,0,8][1,4,0,9]
02-27 414

12-03 486
03-31 227
05-14 486
07-09 228
11-24 42