-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29. Add2Num.cpp
91 lines (80 loc) · 1.89 KB
/
29. Add2Num.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Definition of linked list:
*
* class Node {
* public:
* int data;
* Node *next;
* Node() {
* this->data = 0;
* this->next = NULL;
* }
* Node(int data) {
* this->data = data;
* this->next = NULL;
* }
* Node (int data, Node *next) {
* this->data = data;
* this->next = next;
* }
* };
*
*************************************************************************/
// Node* rev(Node * head){
// Node * prev = nullptr, * curr = head;
// while(curr != nullptr){
// Node * next = curr->next;
// curr->next = prev;
// prev = curr;
// curr = next;
// }
// return prev;
// }
// void dis(Node * head){
// while (head != NULL) {
// cout << head->data << " ";
// head = head->next;
// }
// }
Node *addTwoNumbers(Node *num1, Node *num2){
Node * t1 = num1, *t2 = num2;
int temp = t1->data + t2->data;
int carry = temp/10;
int sum = temp%10;
Node * n = new Node(sum);
Node * nh = n;
t1=t1->next;
t2=t2->next;
while(t1!=nullptr and t2!=nullptr){
temp = carry + t1->data + t2->data;
carry = temp/10;
sum = temp%10;
n->next = new Node(sum);
n = n->next;
t1=t1->next;
t2=t2->next;
}
if(t2==NULL){
while(t1!=nullptr){
// cout<<"l";
temp = t1->data + carry;
carry = temp/10;
sum = temp%10;
n->next = new Node(sum);
n = n->next;
t1=t1->next;
}
}
if(t1==NULL){
while(t2!=nullptr){
temp = t2->data + carry;
carry = temp/10;
sum = temp%10;
n->next = new Node(sum);
n = n->next;
t2=t2->next;
}
}
if(carry!=0)n->next = new Node(carry);
return nh;
}