-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_two_nos.cpp
75 lines (69 loc) · 2 KB
/
add_two_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
64
65
66
67
68
69
70
71
72
73
74
75
#include<iostream>
using namespace std;
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* h1 = l1, *h2 = l2;
int sum = 0, carry = 0;
ListNode *new_head = new ListNode();
ListNode *prev = new_head;
while(h1 && h2) {
ListNode* curr = new ListNode();
prev -> next = curr;
sum = h1 -> val + h2 -> val + carry;
if(sum > 9) {
//carry is first digit and sum is last digit in this case
carry = sum/10;
curr -> val = sum%10;
}
else {
curr -> val = sum;
carry = 0;
}
prev = curr;
h1 = h1 -> next;
h2 = h2 -> next;
if(!h1 and !h2 && carry) {
prev -> next = new ListNode(carry);
}
}
while(h1) {
ListNode* curr = new ListNode();
prev -> next = curr;
sum = h1 -> val + carry;
if(sum > 9) {
carry = sum/10;
curr -> val = sum%10;
}
else {
curr -> val = sum;
carry = 0;
}
prev = curr;
h1 = h1 -> next;
if(!h1 && carry) {
prev -> next = new ListNode(carry);
}
}
while(h2) {
ListNode* curr = new ListNode();
prev -> next = curr;
sum = h2 -> val + carry;
if(sum > 9) {
carry = sum/10;
curr -> val = sum%10;
}
else {
curr -> val = sum;
carry = 0;
}
prev = curr;
h2 = h2 -> next;
if(!h2 && carry) {
prev -> next = new ListNode(carry);
}
}
// if(carry) {
// ListNode* curr = new ListNode(carry);
// prev -> next = curr;
// }
return new_head -> next;
}