-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0008_string_to_integer_atoi.html
More file actions
389 lines (331 loc) · 14.2 KB
/
0008_string_to_integer_atoi.html
File metadata and controls
389 lines (331 loc) · 14.2 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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String to Integer (atoi) - LeetCode 8</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#8</span> String to Integer (atoi)</h1>
<p>Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.</p>
<div class="problem-meta">
<span class="meta-tag">String</span>
<span class="meta-tag">Medium</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0008_string_to_integer_atoi/0008_string_to_integer_atoi.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
</div>
<svg id="mainSvg" width="800" height="350"></svg>
<div class="status-message" id="status">Click "Step" to parse the string</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode String to Integer (atoi)
Problem from LeetCode: https://leetcode.com/problems/string-to-integer-atoi/
Description:
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
6. Return the integer as the final result.
Example 1:
Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
Step 2: "42" (no characters read because there is neither a '-' nor '+')
Step 3: "42" ("42" is read in)
The parsed integer is 42.
Since 42 is in the range [-2^31, 2^31 - 1], the final result is 42.
Example 2:
Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
Step 2: " -42" ('-' is read, so the result should be negative)
Step 3: " -42" ("42" is read in)
The parsed integer is -42.
Since -42 is in the range [-2^31, 2^31 - 1], the final result is -42.
Example 3:
Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
The parsed integer is 4193.
Since 4193 is in the range [-2^31, 2^31 - 1], the final result is 4193.
"""
class Solution:
def my_atoi(self, s: str) -> int:
"""
Convert string to integer according to the atoi algorithm.
Args:
s: Input string
Returns:
int: Converted integer clamped to 32-bit signed integer range
"""
if not s:
return 0
# Step 1: Read in and ignore any leading whitespace
i = 0
while i < len(s) and s[i] == ' ':
i += 1
if i == len(s):
return 0
# Step 2: Check for sign
sign = 1
if s[i] == '-' or s[i] == '+':
sign = -1 if s[i] == '-' else 1
i += 1
# Step 3 & 4: Read digits and convert to number
result = 0
while i < len(s) and s[i].isdigit():
digit = int(s[i])
# Check for overflow before appending digit
if result > (2**31 - 1) // 10 or (result == (2**31 - 1) // 10 and digit > 7):
return 2**31 - 1 if sign == 1 else -2**31
result = result * 10 + digit
i += 1
# Apply sign and check range
result *= sign
# Step 5: Clamp the result
if result < -2**31:
return -2**31
if result > 2**31 - 1:
return 2**31 - 1
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "42"
result1 = solution.my_atoi(s1)
print(f"Example 1: '{s1}' -> {result1}") # Expected output: 42
# Example 2
s2 = " -42"
result2 = solution.my_atoi(s2)
print(f"Example 2: '{s2}' -> {result2}") # Expected output: -42
# Example 3
s3 = "4193 with words"
result3 = solution.my_atoi(s3)
print(f"Example 3: '{s3}' -> {result3}") # Expected output: 4193
# Additional examples
s4 = "words and 987"
result4 = solution.my_atoi(s4)
print(f"Example 4: '{s4}' -> {result4}") # Expected output: 0
s5 = "-91283472332"
result5 = solution.my_atoi(s5)
print(f"Example 5: '{s5}' -> {result5}") # Expected output: -2147483648
</pre>
</div>
</div>
</div>
<script>
const testCases = [
" -42",
"4193 with words",
"words and 987"
];
let currentTest = 0;
let s = testCases[currentTest];
const width = 800, height = 350;
const svg = d3.select("#mainSvg");
const INT_MAX = 2147483647, INT_MIN = -2147483648;
let i = 0;
let phase = 'whitespace'; // whitespace, sign, digits, done
let sign = 1;
let result = 0;
let autoTimer = null;
let autoRunning = false;
function draw() {
svg.selectAll("*").remove();
const cellWidth = 40, startX = 50, startY = 80;
// Title
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Parsing: "${s}"`);
// Draw string characters
for (let idx = 0; idx < s.length; idx++) {
const x = startX + idx * cellWidth;
let fill = "#f8fafc", stroke = "#94a3b8";
if (idx < i) {
fill = "#e0e7ff"; stroke = "#6366f1";
} else if (idx === i) {
fill = "#fef3c7"; stroke = "#f59e0b";
}
svg.append("rect")
.attr("x", x).attr("y", startY)
.attr("width", cellWidth - 4).attr("height", 45)
.attr("rx", 6)
.attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", idx === i ? 3 : 2);
svg.append("text")
.attr("x", x + (cellWidth - 4) / 2)
.attr("y", startY + 30)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(s[idx] === ' ' ? '␣' : s[idx]);
svg.append("text")
.attr("x", x + (cellWidth - 4) / 2)
.attr("y", startY + 60)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#666")
.text(idx);
}
// Pointer
if (i < s.length) {
svg.append("text")
.attr("x", startX + i * cellWidth + (cellWidth - 4) / 2)
.attr("y", startY - 10)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#f59e0b")
.text("▼ i");
}
// Variables
const varsY = 180;
const vars = [
{ name: "Phase", value: phase },
{ name: "Sign", value: sign === 1 ? "+" : "-" },
{ name: "Result", value: result * sign }
];
vars.forEach((v, idx) => {
const x = 100 + idx * 200;
svg.append("rect")
.attr("x", x).attr("y", varsY)
.attr("width", 150).attr("height", 50)
.attr("rx", 8)
.attr("fill", "#e8f5e9").attr("stroke", "#4caf50");
svg.append("text")
.attr("x", x + 75).attr("y", varsY + 20)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(v.name);
svg.append("text")
.attr("x", x + 75).attr("y", varsY + 40)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(v.value);
});
// Final result
if (phase === 'done') {
let finalResult = result * sign;
finalResult = Math.max(INT_MIN, Math.min(INT_MAX, finalResult));
svg.append("rect")
.attr("x", width / 2 - 100).attr("y", 270)
.attr("width", 200).attr("height", 50)
.attr("rx", 10)
.attr("fill", "#d1fae5").attr("stroke", "#10b981");
svg.append("text")
.attr("x", width / 2).attr("y", 302)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`Result: ${finalResult}`);
}
}
function step() {
if (phase === 'done') return false;
if (phase === 'whitespace') {
while (i < s.length && s[i] === ' ') {
i++;
}
document.getElementById("status").textContent = `Skipped whitespace. i = ${i}`;
phase = 'sign';
} else if (phase === 'sign') {
if (i < s.length && (s[i] === '-' || s[i] === '+')) {
sign = s[i] === '-' ? -1 : 1;
document.getElementById("status").textContent = `Found sign: '${s[i]}'. sign = ${sign}`;
i++;
} else {
document.getElementById("status").textContent = "No sign found, defaulting to positive";
}
phase = 'digits';
} else if (phase === 'digits') {
if (i < s.length && /\d/.test(s[i])) {
result = result * 10 + parseInt(s[i]);
document.getElementById("status").textContent =
`Parsed digit '${s[i]}'. result = ${result}`;
i++;
} else {
phase = 'done';
let finalResult = result * sign;
finalResult = Math.max(INT_MIN, Math.min(INT_MAX, finalResult));
document.getElementById("status").textContent =
`Done! Final result: ${finalResult}`;
}
}
draw();
return phase !== 'done';
}
function reset() {
i = 0;
phase = 'whitespace';
sign = 1;
result = 0;
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to parse the string';
draw();
}
function autoRun() {
if (autoRunning) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
autoTimer = setInterval(() => {
if (!step()) {
clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, 800);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>