-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution_AddTwoNumbers.cs
152 lines (129 loc) · 3.29 KB
/
Solution_AddTwoNumbers.cs
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
using System.Text;
namespace LeetCodeTests;
public class Solution_AddTwoNumbers
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
var act1 = l1;
var act2 = l2;
var result = new ListNode();
var pointer = result;
var rem = 0;
while (true)
{
if (act1 is not null && act2 is not null)
{
pointer.val = act1.val + act2.val + rem;
if (pointer.val > 9)
{
pointer.val -= 10;
rem = 1;
}
else
{
rem = 0;
}
act1 = act1.next;
act2 = act2.next;
if (act1 is null && act2 is null)
{
if (rem == 1)
{
pointer.next = new ListNode(1);
}
break;
}
}
else
if (act1 is not null)
{
pointer.val = act1.val + rem;
if (pointer.val > 9)
{
pointer.val -= 10;
rem = 1;
}
else
{
rem = 0;
}
act1 = act1.next;
if (act1 is null)
{
if (rem == 1)
{
pointer.next = new ListNode(1);
}
break;
}
}
else
if (act2 is not null)
{
pointer.val = act2.val + rem;
if (pointer.val > 9)
{
pointer.val -= 10;
rem = 1;
}
else
{
rem = 0;
}
act2 = act2.next;
if (act2 is null)
{
if (rem == 1)
{
pointer.next = new ListNode(1);
}
break;
}
}
pointer.next = new ListNode();
pointer = pointer.next;
}
return result;
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null!)
{
this.val = val;
this.next = next;
}
public override string ToString()
{
var sb = new StringBuilder();
var act = this;
sb.Append('[');
while (act != null)
{
sb.Append(act.val.ToString());
act = act.next;
if (act is not null)
{
sb.Append(',');
}
}
sb.Append(']');
return sb.ToString();
}
public static ListNode FromString(string s)
{
var tmp = new ListNode();
var a = s.Split(',');
var pointer = tmp;
for (int i = 0; i < a.Length; i++)
{
pointer.val = int.Parse(a[i]);
if (i == a.Length - 1) break;
pointer.next = new ListNode();
pointer = pointer.next;
}
return tmp;
}
}