-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_two_numbers.cpp
More file actions
86 lines (78 loc) · 2.09 KB
/
Copy pathadd_two_numbers.cpp
File metadata and controls
86 lines (78 loc) · 2.09 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* Problem statement :- https://leetcode.com/problems/add-two-numbers/description/
*
*/
/**
* 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 *res = NULL, *last = NULL;
int carry = 0, curSum;
while(l1 && l2) {
int v1 = l1->val;
int v2 = l2->val;
curSum = v1 + v2 + carry;
carry = 0;
if(curSum > 9) carry = 1;
curSum = curSum % 10;
if(!res) {
res = new ListNode(curSum);
last = res;
} else{
last->next = new ListNode(curSum);
last = last->next;
}
l1 = l1->next;
l2 = l2->next;
}
while(l1) {
int v = l1->val;
curSum = v + carry;
carry = 0;
if(curSum > 9) carry = 1;
curSum = curSum % 10;
if(!res) {
res = new ListNode(curSum);
last = res;
} else {
last->next = new ListNode(curSum);
last = last->next;
}
l1 = l1->next;
}
while(l2) {
int v = l2->val;
curSum = v + carry;
carry = 0;
if(curSum > 9) carry = 1;
curSum = curSum % 10;
if(!res) {
res = new ListNode(curSum);
last = res;
} else {
last->next = new ListNode(curSum);
last = last->next;
}
l2 = l2->next;
}
if(carry) {
if(!res) {
res = new ListNode(carry);
last = res;
} else {
last->next = new ListNode(carry);
last = last->next;
}
}
if(last)
last->next = NULL;
return res;
}
};