-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.cpp
More file actions
61 lines (56 loc) · 1.16 KB
/
2.cpp
File metadata and controls
61 lines (56 loc) · 1.16 KB
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
/**
* 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* ptr;
ListNode* newNode;
ListNode* result;
int add1, add2;
int temp;
bool carry;
carry = false;
temp = l1->val + l2->val;
if (temp >= 10) {
newNode = new ListNode(temp - 10);
carry = true;
} else {
newNode = new ListNode(temp);
}
ptr = result = newNode;
while(1) {
if (l1) {
l1 = l1->next;
add1 = l1 ? l1->val : 0;
} else {
add1 = 0;
}
if (l2) {
l2 = l2->next;
add2 = l2 ? l2->val : 0;
} else {
add2 = 0;
}
if (!l1 && !l2 && carry == 0 ) {
break;
}
temp = add1 + add2 + carry;
carry = false;
if (temp >= 10) {
newNode = new ListNode(temp - 10);
carry = true;
} else {
newNode = new ListNode(temp);
}
ptr->next = newNode;
ptr = newNode;
}
return result;
}
};