-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_ADD_TWO_NUMBERS.cpp
54 lines (42 loc) · 989 Bytes
/
2_ADD_TWO_NUMBERS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int tmp_num = 0;
int carry = 0;
ListNode* res = new ListNode(0);
ListNode* pre = res;
while( l1 != NULL || l2 != NULL)
{
tmp_num += (l1 == NULL)? 0: l1->val;
tmp_num += (l2 == NULL)? 0: l2->val;
tmp_num += carry;
carry = tmp_num / 10;
tmp_num %= 10;
pre->next = new ListNode(tmp_num);
pre = pre->next;
l1 = (l1 == NULL)? l1: l1->next;
l2 = (l2 == NULL)? l2: l2->next;
tmp_num = 0;
}
if(carry == 1)
pre->next = new ListNode(carry);
return res->next;
}
};
int main()
{
ListNode* l1 = new ListNode(0);
auto tmp = l1;
ListNode* l2 = new ListNode(1);
tmp = l2;
tmp->next = new ListNode(8);
auto res = Solution().addTwoNumbers(l1, l2);
cout << "res is " << res->val << endl;
}