Having fun on Leetcode with C++, Java, Python & GO
Problem 2. Add Two Numbers
My attempt(s)
Code
C++
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
|
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *temp1 = l1;
ListNode *temp2 = l2;
ListNode *l3 = new ListNode;
ListNode *temp = l3;
while(temp1!=NULL)
{
temp->val=temp1->val;
temp1=temp1->next;
if (temp1!=NULL)
temp->next = new ListNode;
temp=temp->next;
}
temp1 = l1;
temp = l3;
while(temp2!=NULL)
{
if (temp1!=NULL)
temp->val=temp->val+temp2->val;
else
temp->val=temp->val+temp2->val;
temp2=temp2->next;
if(temp1!=NULL)
if(temp1->next!=NULL)
temp1=temp1->next;
else
temp1=NULL;
if (temp2!=NULL && temp->next==NULL)
temp->next = new ListNode;
temp=temp->next;
}
temp=l3;
while(temp!=NULL)
{
if (temp->val>9)
{
temp->val=temp->val%10;
if (temp->next!=NULL)
temp->next->val+=1;
else
temp->next=new ListNode(1);
}
temp=temp->next;
}
return l3;
}
};
|
C++
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
|
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *temp1 = l1;
ListNode *temp2 = l2;
ListNode *l3 = new ListNode;
ListNode *temp = l3;
while(temp1!=NULL)
{
temp->val=temp1->val;
temp1=temp1->next;
if (temp1!=NULL)
temp->next = new ListNode;
temp=temp->next;
}
temp1 = l1;
temp = l3;
while(temp2!=NULL)
{
if (temp1!=NULL)
temp->val=temp->val+temp2->val;
else
temp->val=temp->val+temp2->val;
temp2=temp2->next;
if(temp1!=NULL)
if(temp1->next!=NULL)
temp1=temp1->next;
else
temp1=NULL;
if (temp2!=NULL && temp->next==NULL)
temp->next = new ListNode;
temp=temp->next;
}
temp=l3;
while(temp!=NULL)
{
if (temp->val>9)
{
temp->val=temp->val%10;
if (temp->next!=NULL)
temp->next->val+=1;
else
temp->next=new ListNode(1);
}
temp=temp->next;
}
return l3;
}
};
|
Explanation of idea
Good solution ref.
Code
Analysis