-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0007_reverse_integer.html
More file actions
381 lines (321 loc) · 14.6 KB
/
Copy path0007_reverse_integer.html
File metadata and controls
381 lines (321 loc) · 14.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 7: Reverse Integer - Algorithm Visualization</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">#7</span> Reverse Integer</h1>
<p>Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], return 0.</p>
<div class="problem-meta">
<span class="meta-tag">🔢 Math</span>
<span class="meta-tag">📊 Modulo</span>
<span class="meta-tag">⏱️ O(log n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0007_reverse_integer/0007_reverse_integer.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Reversing a number is like <strong>moving digits one by one</strong> from the end to build a new number:</p>
<ul>
<li><strong>Pop last digit:</strong> Use <code>x % 10</code> to get the last digit</li>
<li><strong>Remove last digit:</strong> Use <code>x // 10</code> to shrink the number</li>
<li><strong>Push to result:</strong> Use <code>result * 10 + digit</code> to build reversed number</li>
<li><strong>Check overflow:</strong> Ensure result stays within 32-bit range</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<input type="number" id="numberInput" value="12345" style="width: 120px; padding: 10px; border-radius: 8px; border: 2px solid #ddd;">
<button class="btn btn-primary" onclick="setNumber()">Set Number</button>
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Enter a number and click Step to begin
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 20px 0;">
<div class="array-section">
<div class="array-label">📥 Original Number</div>
<div id="originalViz" class="array-container" style="justify-content: center; padding: 20px; background: #f5f5f5; border-radius: 12px; min-height: 100px;"></div>
</div>
<div class="array-section">
<div class="array-label">📤 Reversed Number</div>
<div id="resultViz" class="array-container" style="justify-content: center; padding: 20px; background: #e8f5e9; border-radius: 12px; min-height: 100px;"></div>
</div>
</div>
<div class="array-section">
<div class="array-label">⚙️ Current Operation</div>
<div id="operationArea" style="padding: 20px; background: #f5f5f5; border-radius: 12px; text-align: center; font-family: monospace; font-size: 1.1em;">
Click Step or Auto Run to begin
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Reverse Integer
Problem from LeetCode: https://leetcode.com/problems/reverse-integer/
Description:
Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
"""
class Solution:
def reverse(self, x: int) ->int:
"""
Reverse the digits of a 32-bit signed integer.
Args:
x: The integer to reverse
Returns:
int: The reversed integer, or 0 if the result would overflow
"""
INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
sign = -1 if x < 0 else 1
x = abs(x)
rev = 0
while x != 0:
pop = x % 10
x //= 10
if rev > INT_MAX // 10 or rev == INT_MAX // 10 and pop > 7:
return 0
rev = rev * 10 + pop
return sign * rev
def reverse_pythonic(self, x: int) ->int:
"""
Alternative implementation using Python's string conversion and slicing.
Args:
x: The integer to reverse
Returns:
int: The reversed integer, or 0 if the result would overflow
"""
INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
sign = -1 if x < 0 else 1
rev = sign * int(str(abs(x))[::-1])
if rev < INT_MIN or rev > INT_MAX:
return 0
return rev
def reverse_clean(self, x: int) ->int:
"""
A cleaner approach without separating sign handling.
Note: This method handles Python's floor division semantics correctly.
Args:
x: The integer to reverse
Returns:
int: The reversed integer, or 0 if the result would overflow
"""
INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
# Handle negative numbers by working with absolute value
sign = -1 if x < 0 else 1
x = abs(x)
rev = 0
while x != 0:
digit = x % 10
x //= 10
# Check for overflow before multiplying
if rev > INT_MAX // 10 or (rev == INT_MAX // 10 and digit > 7):
return 0
rev = rev * 10 + digit
result = sign * rev
# Final overflow check for negative result
if result < INT_MIN or result > INT_MAX:
return 0
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
x1 = 123
result1 = solution.reverse(x1)
print(f"Example 1: {x1} -> {result1}") # Expected output: 321
# Example 2
x2 = -123
result2 = solution.reverse(x2)
print(f"Example 2: {x2} -> {result2}") # Expected output: -321
# Example 3
x3 = 120
result3 = solution.reverse(x3)
print(f"Example 3: {x3} -> {result3}") # Expected output: 21
# Test overflow case
x4 = 1534236469
result4 = solution.reverse(x4)
print(f"Overflow test: {x4} -> {result4}") # Expected output: 0 (would overflow)
# Compare implementations
print("\nUsing alternative implementations:")
print(f"Pythonic method for {x1}: {solution.reverse_pythonic(x1)}")
print(f"Clean method for {x2}: {solution.reverse_clean(x2)}")
</pre>
</div>
</div>
</div>
<script>
const INT_MAX = 2147483647;
const INT_MIN = -2147483648;
let originalNumber = 12345;
let x = 0;
let result = 0;
let sign = 1;
let steps = [];
let stepIndex = 0;
let autoInterval = null;
let isComplete = false;
function setNumber() {
const input = parseInt(document.getElementById('numberInput').value);
if (!isNaN(input)) {
originalNumber = input;
reset();
}
}
function reset() {
sign = originalNumber >= 0 ? 1 : -1;
x = Math.abs(originalNumber);
result = 0;
steps = [];
stepIndex = 0;
isComplete = false;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = 'Auto Run';
}
// Build all steps
let tempX = x;
let tempResult = 0;
while (tempX !== 0) {
const digit = tempX % 10;
const newX = Math.floor(tempX / 10);
const newResult = tempResult * 10 + digit;
steps.push({
x: tempX,
digit: digit,
newX: newX,
result: tempResult,
newResult: newResult,
overflow: Math.abs(newResult) > INT_MAX
});
tempX = newX;
tempResult = newResult;
}
render();
document.getElementById('statusMessage').textContent = 'Enter a number and click Step to begin';
}
function step() {
if (isComplete || stepIndex >= steps.length) {
isComplete = true;
render();
return;
}
stepIndex++;
render();
}
function toggleAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = 'Auto Run';
} else {
autoInterval = setInterval(() => {
if (stepIndex >= steps.length) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = 'Auto Run';
isComplete = true;
render();
} else {
step();
}
}, 1000);
document.getElementById('autoBtn').textContent = 'Pause';
}
}
function render() {
const originalViz = document.getElementById('originalViz');
const resultViz = document.getElementById('resultViz');
const operationArea = document.getElementById('operationArea');
const originalDigits = Math.abs(originalNumber).toString().split('');
const processedCount = stepIndex;
// Render original number
let originalHtml = '';
if (sign < 0) {
originalHtml += '<div class="array-box" style="background: #ffcdd2; border-color: #f44336; width: 50px;">−</div>';
}
originalDigits.forEach((d, i) => {
const revIndex = originalDigits.length - 1 - i;
let style = '';
if (revIndex < processedCount) {
style = 'background: #c8e6c9; border-color: #4caf50;';
} else if (revIndex === processedCount && stepIndex > 0) {
style = 'background: #fff9c4; border-color: #fbc02d; transform: scale(1.1);';
}
originalHtml += `<div class="array-box" style="${style}">${d}</div>`;
});
originalViz.innerHTML = originalHtml;
// Render result number
let currentResult = 0;
if (stepIndex > 0) {
currentResult = steps[stepIndex - 1].newResult;
}
const resultStr = currentResult.toString();
let resultHtml = '';
if (sign < 0 && currentResult > 0) {
resultHtml += '<div class="array-box" style="background: #ffcdd2; border-color: #f44336; width: 50px;">−</div>';
}
if (currentResult === 0 && stepIndex === 0) {
resultHtml += '<div class="array-box" style="opacity: 0.5;">0</div>';
} else {
resultStr.split('').forEach((d) => {
resultHtml += `<div class="array-box" style="background: #c8e6c9; border-color: #4caf50;">${d}</div>`;
});
}
resultViz.innerHTML = resultHtml;
// Render operation
if (stepIndex > 0 && stepIndex <= steps.length) {
const s = steps[stepIndex - 1];
operationArea.innerHTML = `
<div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">
<span style="padding: 10px 15px; background: #e3f2fd; border-radius: 8px;">digit = ${s.x} % 10 = <strong>${s.digit}</strong></span>
<span style="padding: 10px 15px; background: #f5f5f5; border-radius: 8px;">x = ${s.x} / 10 = ${s.newX}</span>
<span style="padding: 10px 15px; background: #e8f5e9; border-radius: 8px;">result = ${s.result} × 10 + ${s.digit} = <strong>${s.newResult}</strong></span>
</div>
${s.overflow ? '<div style="margin-top: 15px; padding: 10px; background: #ffebee; border-radius: 8px; color: #c62828;">⚠️ Overflow detected! Would return 0</div>' : ''}
`;
document.getElementById('statusMessage').textContent = `Step ${stepIndex}: Pop digit ${s.digit}, result = ${s.newResult}`;
} else if (isComplete) {
const finalResult = sign * (steps.length > 0 ? steps[steps.length - 1].newResult : 0);
const overflow = Math.abs(finalResult) > INT_MAX;
operationArea.innerHTML = `
<div style="font-size: 1.4em; color: #4caf50; font-weight: bold;">
Final Result: ${overflow ? 0 : finalResult}
</div>
${overflow ? '<div style="margin-top: 15px; padding: 10px; background: #ffebee; border-radius: 8px; color: #c62828;">⚠️ Overflow! Return 0</div>' : ''}
`;
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent = `✅ Complete! Reversed: ${overflow ? 0 : finalResult}`;
} else {
operationArea.innerHTML = 'Click Step or Auto Run to begin';
}
}
reset();
</script>
</body>
</html>