-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20170720 - Add Two Numbers - Meduim
66 lines (54 loc) · 1.52 KB
/
20170720 - Add Two Numbers - Meduim
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
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* i1 = l1;
ListNode* i2 = l2;
ListNode* head;
ListNode* add;
ListNode* before;
int m = 0;
add = new ListNode(0);
if (i1 != NULL) add->val = add->val + i1->val;
if (i2 != NULL) add->val = add->val + i2->val;
if (add->val >= 10)
{
m = (int)( add->val / 10 ) ;
add->val = add->val % 10;
}
head = add;
if (i1 != NULL) i1 = i1->next;
if (i2 != NULL) i2 = i2->next;
while(i1 != NULL || i2 != NULL)
{
before = add;
add = new ListNode(m);
if (i1 != NULL) add->val = add->val + i1->val;
if (i2 != NULL) add->val = add->val + i2->val;
m = 0;
if (add->val >= 10)
{
m = (int)( add->val / 10 ) ;
add->val = add->val % 10;
}
before->next = add;
if (i1 != NULL) i1 = i1->next;
if (i2 != NULL) i2 = i2->next;
};
if (m != 0)
{
before = add;
add = new ListNode(m);
before->next = add;
}
add->next = NULL;
return head;
}
};