-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2. Add Two Numbers
More file actions
48 lines (47 loc) · 1.5 KB
/
Copy path2. Add Two Numbers
File metadata and controls
48 lines (47 loc) · 1.5 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* h1, ListNode* h2) {
ListNode* res= new ListNode(0);
ListNode* temp=res;
int rem=0,sum=0;
while(h1 || h2){
if(h1 && h2){ sum = (h1->val)+(h2->val);
h1=h1->next;
h2=h2->next;
}
else if(h1){ sum = (h1->val);
h1=h1->next;
}
else{
sum = (h2->val);
h2=h2->next;
}
////////////////////////////////////////////////
if((sum+rem)>9){
sum+=rem;
sum %=10;
temp->next=new ListNode(sum);
rem=1;
}
else{
temp->next=new ListNode(sum+rem);
rem=0;
}
temp=temp->next; //we have to move temp too
}
if(rem==1 && !h1 && !h2){ temp->next=new ListNode(rem);}
return res->next;
}
};
/*Runtime: 20 ms, faster than 97.05% of C++ online submissions for Add Two Numbers.
Memory Usage: 71.5 MB, less than 49.42% of C++ online submissions for Add Two Numbers.*/