-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path029_Add Two Numbers.cpp
63 lines (42 loc) · 1009 Bytes
/
029_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
Node *addTwoNumbers(Node *num1, Node *num2)
{
// Write your code here.
Node* dummy = new Node(0);
Node* head = dummy;
int carry = 0, sum = 0;
while(num1 and num2)
{
sum = carry + num1->data + num2->data;
Node* temp = new Node(sum%10);
carry = sum/10;
num1 = num1->next;
num2 = num2->next;
dummy->next = temp;
dummy = dummy->next;
}
while(num1)
{
sum = carry + num1->data;
Node* temp = new Node(sum%10);
carry = sum/10;
num1 = num1->next;
dummy->next = temp;
dummy = dummy->next;
}
while(num2)
{
sum = carry + num2->data;
Node* temp = new Node(sum%10);
carry = sum/10;
num2 = num2->next;
dummy->next = temp;
dummy = dummy->next;
}
if(carry)
{
Node* temp = new Node(carry);
dummy->next = temp;
dummy = dummy->next;
}
return head->next;
}