-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-2-nos.cpp
63 lines (61 loc) · 1.1 KB
/
add-2-nos.cpp
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
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* insert(ListNode* ptr,int key)
{
ListNode* temp=new ListNode(key);
temp->next=ptr;
return temp;
}
ListNode* add(ListNode* l1,ListNode* l2)
{
int temp=0;
ListNode* carry;
if(l1->next&&l2->next)
{
carry = add(l1->next,l2->next);
temp=carry->val+l1->val+l2->val;
carry->val=temp%10;
temp/=10;
carry=insert(carry,temp);
return carry;
}
else if(l1->next&&!l2->next)
{
carry = add(l1->next,l2);
temp=l1->val+carry->val;
carry->val=temp%10;
temp/=10;
carry=insert(carry,temp);
return carry;
}
else if(!l1->next&&l2->next)
{
carry = add(l1,l2->next);
temp=l2->val+carry->val;
carry->val=temp%10;
temp/=10;
carry=insert(carry,temp);
return carry;
}
else
{
temp=(l1->val+l2->val);
carry=insert(carry,temp%10);
temp/=10;
carry=insert(carry,temp);
return carry;
}
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* carry;
carry=add(l1,l2);
if(carry->val==0)
carry=carry->next;
return carry;
}
};