Skip to content

Commit 0abe59c

Browse files
Merge pull request #80 from gantavya123/patch-2
Create add-two-numbers.cpp
2 parents fa59721 + 4661dc0 commit 0abe59c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

CPP/Problems/add-two-numbers.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
14+
ListNode* dummy = new ListNode(0);
15+
ListNode* ll = dummy;
16+
int carry = 0;
17+
int sum = 0;
18+
while(l1 and l2){
19+
sum = l1->val + l2->val + carry;
20+
ll->next = new ListNode(sum%10);
21+
ll = ll->next;
22+
carry = sum/10;
23+
l1 = l1->next;
24+
l2 = l2->next;
25+
}
26+
while(l1){
27+
sum = l1->val + carry;
28+
ll->next = new ListNode(sum%10);
29+
ll = ll->next;
30+
carry = sum/10;
31+
l1 = l1->next;
32+
33+
}
34+
while(l2){
35+
sum = l2->val + carry;
36+
ll->next = new ListNode(sum%10);
37+
ll = ll->next;
38+
carry = sum/10;
39+
l2 = l2->next;
40+
}
41+
if(carry != 0){
42+
ll->next = new ListNode(carry);
43+
ll = ll->next;
44+
}
45+
return dummy->next;
46+
}
47+
};

0 commit comments

Comments
 (0)