Skip to content

Commit 43971d3

Browse files
committed
add-two-numbers
1 parent 9e84852 commit 43971d3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

add-two-numbers.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
4+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
5+
6+
struct ListNode* result;
7+
struct ListNode* temp;
8+
int carry = 0;
9+
int f = 1;
10+
while(l1!=NULL || l2!=NULL)
11+
{
12+
int x = (l1!=NULL)?l1->val:0;
13+
int y = (l2!=NULL)?l2->val:0;
14+
15+
int sum = x + y + carry;
16+
carry = sum/10;
17+
if(f)
18+
{
19+
result = new ListNode(sum%10);
20+
temp = result;
21+
f = 0;
22+
}
23+
else
24+
{
25+
result->next = new ListNode(sum%10);
26+
result = result->next;
27+
}
28+
29+
if(l1!=NULL) l1 = l1->next;
30+
if(l2!=NULL) l2 = l2->next;
31+
}
32+
if(carry)
33+
result->next = new ListNode(carry);
34+
35+
return temp;
36+
}
37+
};

0 commit comments

Comments
 (0)