-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAdd Two Numbers
More file actions
117 lines (109 loc) · 3.19 KB
/
Add Two Numbers
File metadata and controls
117 lines (109 loc) · 3.19 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int extra_bit = 0;
ListNode *l3 = NULL;
ListNode *curr = NULL;
int val;
while(l1 || l2)
{
if(l1&&l2)
{
val = l1->val + l2->val + extra_bit;
if(val>=10)
{
extra_bit = 1;
val = val-10;
}
else
extra_bit = 0;
if(l3==NULL)
{
l3 = new ListNode(val);
curr = l3;
}
else
{
ListNode *add_node = new ListNode(val);
curr->next = add_node;
curr = curr->next;
}
l1 = l1->next;
l2 = l2->next;
}
else if(l1)
{
val = l1->val + extra_bit;
if(val>=10) { val = val-10;extra_bit = 1;}
else extra_bit = 0;
if(l3==NULL)
{
l3 = new ListNode(val);
curr = l3;
}
else
{
ListNode *add_node = new ListNode(val);
curr->next = add_node;
curr = curr->next;
}
l1 = l1->next;
}
else if(l2)
{
val = l2->val + extra_bit;
if(val>=10) { val = val-10;extra_bit = 1;}
else extra_bit = 0;
if(l3==NULL)
{
l3 = new ListNode(val);
curr = l3;
}
else
{
ListNode *add_node = new ListNode(val);
curr->next = add_node;
curr = curr->next;
}
l2 = l2->next;
}
}
if(extra_bit)
{
ListNode *add_node = new ListNode(1);
curr->next = add_node;
curr = curr->next;
}
return l3;
}
};
/******soultion from online *******/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode *p1 = l1, *p2 = l2, *p3 = &dummy;
int carry = 0;
while (p1 || p2 || carry) {
int sum = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + carry;
int value = sum % 10;
carry = sum / 10;
p3->next = new ListNode(value);
p3 = p3->next;
p1 = p1 ? p1->next : 0;
p2 = p2 ? p2->next : 0;
}
return dummy.next;
}
};