-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_Two_Numbers.cpp
63 lines (59 loc) · 1.32 KB
/
Add_Two_Numbers.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
/**
* 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 *addTwoNumbers(Node *num1, Node *num2)
{
// Write your code here.
int carry = 0;
Node *num3 = new Node();
Node *head = num3;
while (num1 && num2)
{
int value = num1->data + num2->data + carry;
carry = value / 10;
num3->next = new Node(value % 10);
num1 = num1->next;
num2 = num2->next;
num3 = num3->next;
}
while (num1)
{
int value = num1->data + carry;
carry = value / 10;
num3->next = new Node(value % 10);
num1 = num1->next;
num3 = num3->next;
}
while (num2)
{
int value = num2->data + carry;
carry = value / 10;
num3->next = new Node(value % 10);
num2 = num2->next;
num3 = num3->next;
}
if (carry)
{
num3->next = new Node(carry);
}
return head->next;
}