-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0013_roman_to_integer.html
More file actions
421 lines (354 loc) · 14.2 KB
/
0013_roman_to_integer.html
File metadata and controls
421 lines (354 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Roman to Integer - LeetCode 13</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">#13</span> Roman to Integer</h1>
<p>Convert a Roman numeral to an integer.</p>
<div class="problem-meta">
<span class="meta-tag">Math</span>
<span class="meta-tag">String</span>
<span class="meta-tag">Easy</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0013_roman_to_integer/0013_roman_to_integer.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="380"></svg>
<div class="status-message" id="status">Click "Step" to convert Roman to integer</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Roman to Integer
Problem from LeetCode: https://leetcode.com/problems/roman-to-integer/
Description:
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together.
12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII.
Instead, the number four is written as IV. Because the one is before the five we subtract it making four.
The same principle applies to the number nine, which is written as IX.
There are six instances where subtraction is used:
- I can be placed before V (5) and X (10) to make 4 and 9.
- X can be placed before L (50) and C (100) to make 40 and 90.
- C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
"""
class Solution:
def roman_to_int(self, s: str) -> int:
"""
Convert a Roman numeral to an integer.
Args:
s: A string representing a valid Roman numeral in the range [1, 3999]
Returns:
int: The integer value of the Roman numeral
"""
# Define the mapping of Roman numerals to integers
values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
total = 0
i = 0
while i < len(s):
# If this is the subtractive case
if i + 1 < len(s) and values[s[i]] < values[s[i + 1]]:
total += values[s[i + 1]] - values[s[i]]
i += 2
# Else this is regular case
else:
total += values[s[i]]
i += 1
return total
def roman_to_int_simpler(self, s: str) -> int:
"""
A simpler implementation that processes the string from right to left.
Args:
s: A string representing a valid Roman numeral
Returns:
int: The integer value of the Roman numeral
"""
values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
total = 0
prev_value = 0
# Process the string from right to left
for char in reversed(s):
current_value = values[char]
# If current value is greater than or equal to previous value, add it
if current_value >= prev_value:
total += current_value
# Otherwise, subtract it (handles cases like IV, IX, etc.)
else:
total -= current_value
prev_value = current_value
return total
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "III"
result1 = solution.roman_to_int(s1)
print(f"Example 1: '{s1}' -> {result1}") # Expected output: 3
# Example 2
s2 = "LVIII"
result2 = solution.roman_to_int(s2)
print(f"Example 2: '{s2}' -> {result2}") # Expected output: 58
# Example 3
s3 = "MCMXCIV"
result3 = solution.roman_to_int(s3)
print(f"Example 3: '{s3}' -> {result3}") # Expected output: 1994
# Additional examples
s4 = "MMXXIII"
result4 = solution.roman_to_int(s4)
print(f"Example 4: '{s4}' -> {result4}") # Expected output: 2023
# Compare with simpler implementation
print("\nUsing simpler approach (right to left):")
print(f"Example 1: '{s1}' -> {solution.roman_to_int_simpler(s1)}")
print(f"Example 2: '{s2}' -> {solution.roman_to_int_simpler(s2)}")
print(f"Example 3: '{s3}' -> {solution.roman_to_int_simpler(s3)}")
</pre>
</div>
</div>
</div>
<script>
const romanValues = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};
const testCases = ["MCMXCIV", "III", "LVIII", "IX"];
let s = "MCMXCIV";
let i;
let total = 0;
let prevValue = 0;
let phase = 'processing';
const width = 800, height = 380;
const svg = d3.select("#mainSvg");
let autoTimer = null;
let autoRunning = false;
function draw() {
svg.selectAll("*").remove();
const cellWidth = 60, startX = 100, startY = 80;
// Title
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Converting "${s}" to Integer (Right to Left)`);
// Draw Roman characters
for (let idx = 0; idx < s.length; idx++) {
const x = startX + idx * cellWidth;
const isProcessed = idx > i;
const isCurrent = idx === i;
svg.append("rect")
.attr("x", x).attr("y", startY)
.attr("width", cellWidth - 5).attr("height", 55)
.attr("rx", 8)
.attr("fill", isCurrent ? "#fef3c7" : (isProcessed ? "#d1fae5" : "#e3f2fd"))
.attr("stroke", isCurrent ? "#f59e0b" : (isProcessed ? "#10b981" : "#1976d2"))
.attr("stroke-width", isCurrent ? 3 : 2);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 30)
.attr("text-anchor", "middle")
.attr("font-size", "26px")
.attr("font-weight", "bold")
.text(s[idx]);
svg.append("text")
.attr("x", x + (cellWidth - 5) / 2)
.attr("y", startY + 48)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(romanValues[s[idx]]);
}
// Direction arrow
svg.append("text")
.attr("x", startX + s.length * cellWidth + 20)
.attr("y", startY + 30)
.attr("font-size", "24px")
.text("←");
svg.append("text")
.attr("x", startX + s.length * cellWidth + 50)
.attr("y", startY + 35)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("Direction");
// Variables display
const varsY = 180;
const vars = [
{ name: "Current Value", value: i >= 0 ? romanValues[s[i]] : "-" },
{ name: "Previous Value", value: prevValue },
{ name: "Total", value: total }
];
vars.forEach((v, idx) => {
const x = 100 + idx * 200;
svg.append("rect")
.attr("x", x).attr("y", varsY)
.attr("width", 160).attr("height", 60)
.attr("rx", 10)
.attr("fill", idx === 2 ? "#e8f5e9" : "#f5f5f5")
.attr("stroke", idx === 2 ? "#4caf50" : "#ddd");
svg.append("text")
.attr("x", x + 80).attr("y", varsY + 22)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(v.name);
svg.append("text")
.attr("x", x + 80).attr("y", varsY + 48)
.attr("text-anchor", "middle")
.attr("font-size", "22px")
.attr("font-weight", "bold")
.text(v.value);
});
// Logic explanation
if (i >= 0 && phase === 'processing') {
const curr = romanValues[s[i]];
const logicY = 280;
const isSubtraction = curr < prevValue;
svg.append("rect")
.attr("x", 150).attr("y", logicY)
.attr("width", 500).attr("height", 45)
.attr("rx", 8)
.attr("fill", isSubtraction ? "#fee2e2" : "#d1fae5")
.attr("stroke", isSubtraction ? "#ef4444" : "#10b981");
svg.append("text")
.attr("x", 400).attr("y", logicY + 28)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.text(isSubtraction
? `${curr} < ${prevValue}: SUBTRACT → total = ${total} - ${curr}`
: `${curr} ≥ ${prevValue}: ADD → total = ${total} + ${curr}`);
}
// Final result
if (phase === 'done') {
svg.append("rect")
.attr("x", width / 2 - 120).attr("y", 310)
.attr("width", 240).attr("height", 55)
.attr("rx", 12)
.attr("fill", "#d1fae5").attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", width / 2).attr("y", 345)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`${s} = ${total}`);
}
}
function step() {
if (phase === 'done') return false;
if (i < 0) {
phase = 'done';
document.getElementById("status").textContent = `Done! ${s} = ${total}`;
draw();
return false;
}
const curr = romanValues[s[i]];
if (curr >= prevValue) {
total += curr;
document.getElementById("status").textContent =
`'${s[i]}' (${curr}) ≥ prev (${prevValue}): Add ${curr}. Total = ${total}`;
} else {
total -= curr;
document.getElementById("status").textContent =
`'${s[i]}' (${curr}) < prev (${prevValue}): Subtract ${curr}. Total = ${total}`;
}
prevValue = curr;
i--;
draw();
return i >= 0;
}
function reset() {
i = s.length - 1;
total = 0;
prevValue = 0;
phase = 'processing';
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to convert Roman to integer';
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);
reset();
</script>
</body>
</html>