-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0012_integer_to_roman.html
More file actions
391 lines (329 loc) · 14.2 KB
/
0012_integer_to_roman.html
File metadata and controls
391 lines (329 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Integer to Roman - LeetCode 12</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">#12</span> Integer to Roman</h1>
<p>Convert an integer to a Roman numeral.</p>
<div class="problem-meta">
<span class="meta-tag">Math</span>
<span class="meta-tag">String</span>
<span class="meta-tag">Medium</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0012_integer_to_roman/0012_integer_to_roman.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>
<label style="margin-left:20px">Number: </label>
<input type="number" id="numInput" value="1994" min="1" max="3999" style="width:80px">
</div>
<svg id="mainSvg" width="800" height="420"></svg>
<div class="status-message" id="status">Click "Step" to convert to Roman numeral</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Integer to Roman
Problem from LeetCode: https://leetcode.com/problems/integer-to-roman/
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 one's 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 an integer, convert it to a roman numeral.
Example 1:
Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.
Example 2:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
"""
class Solution:
def int_to_roman(self, num: int) -> str:
"""
Convert an integer to its Roman numeral representation.
Args:
num: An integer in the range [1, 3999]
Returns:
str: Roman numeral representation of the input
"""
# Define the mapping of values to Roman numerals
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
numerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
result = ""
# Iterate through each value-numeral pair
for i in range(len(values)):
# Add the numeral as many times as possible
while num >= values[i]:
result += numerals[i]
num -= values[i]
return result
def int_to_roman_direct_mapping(self, num: int) -> str:
"""
Alternative implementation using direct mapping of digit positions.
Args:
num: An integer in the range [1, 3999]
Returns:
str: Roman numeral representation of the input
"""
# Define mappings for each place value
thousands = ["", "M", "MM", "MMM"]
hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
# Combine the Roman numerals for each place value
return (thousands[num // 1000] +
hundreds[(num % 1000) // 100] +
tens[(num % 100) // 10] +
ones[num % 10])
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
num1 = 3
result1 = solution.int_to_roman(num1)
print(f"Example 1: {num1} -> {result1}") # Expected output: "III"
# Example 2
num2 = 58
result2 = solution.int_to_roman(num2)
print(f"Example 2: {num2} -> {result2}") # Expected output: "LVIII"
# Example 3
num3 = 1994
result3 = solution.int_to_roman(num3)
print(f"Example 3: {num3} -> {result3}") # Expected output: "MCMXCIV"
# Additional examples
num4 = 2023
result4 = solution.int_to_roman(num4)
print(f"Example 4: {num4} -> {result4}") # Expected output: "MMXXIII"
# Compare with direct mapping implementation
print("\nUsing direct mapping approach:")
print(f"Example 1: {num1} -> {solution.int_to_roman_direct_mapping(num1)}")
print(f"Example 2: {num2} -> {solution.int_to_roman_direct_mapping(num2)}")
print(f"Example 3: {num3} -> {solution.int_to_roman_direct_mapping(num3)}")
</pre>
</div>
</div>
</div>
<script>
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
let num = 1994;
let remaining;
let result = "";
let currentIndex = 0;
let phase = 'checking';
const width = 800, height = 420;
const svg = d3.select("#mainSvg");
let autoTimer = null;
let autoRunning = false;
function draw() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Converting ${num} to Roman Numerals`);
// Value-Symbol table
const tableX = 50, tableY = 60;
const cellW = 55, cellH = 35;
svg.append("text")
.attr("x", tableX).attr("y", tableY - 5)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("Value → Symbol mapping:");
values.forEach((val, i) => {
const x = tableX + (i % 7) * cellW;
const y = tableY + Math.floor(i / 7) * (cellH + 5);
const isCurrent = i === currentIndex;
svg.append("rect")
.attr("x", x).attr("y", y)
.attr("width", cellW - 3).attr("height", cellH)
.attr("rx", 4)
.attr("fill", isCurrent ? "#fef3c7" : (i < currentIndex ? "#e0e0e0" : "#e3f2fd"))
.attr("stroke", isCurrent ? "#f59e0b" : "#1976d2")
.attr("stroke-width", isCurrent ? 2 : 1);
svg.append("text")
.attr("x", x + (cellW - 3) / 2).attr("y", y + 15)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#666")
.text(val);
svg.append("text")
.attr("x", x + (cellW - 3) / 2).attr("y", y + 28)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(symbols[i]);
});
// Current state
const stateY = 180;
// Remaining value
svg.append("rect")
.attr("x", 50).attr("y", stateY)
.attr("width", 180).attr("height", 60)
.attr("rx", 10)
.attr("fill", "#fff3e0").attr("stroke", "#ff9800");
svg.append("text")
.attr("x", 140).attr("y", stateY + 20)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text("Remaining");
svg.append("text")
.attr("x", 140).attr("y", stateY + 45)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.text(remaining);
// Result so far
svg.append("rect")
.attr("x", 250).attr("y", stateY)
.attr("width", 500).attr("height", 60)
.attr("rx", 10)
.attr("fill", "#e8f5e9").attr("stroke", "#4caf50");
svg.append("text")
.attr("x", 500).attr("y", stateY + 20)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text("Result");
svg.append("text")
.attr("x", 500).attr("y", stateY + 48)
.attr("text-anchor", "middle")
.attr("font-size", "28px")
.attr("font-weight", "bold")
.attr("fill", "#2e7d32")
.text(result || "(empty)");
// Calculation display
if (currentIndex < values.length && remaining >= values[currentIndex]) {
const calcY = 280;
svg.append("rect")
.attr("x", 200).attr("y", calcY)
.attr("width", 400).attr("height", 50)
.attr("rx", 8)
.attr("fill", "#e3f2fd").attr("stroke", "#1976d2");
svg.append("text")
.attr("x", 400).attr("y", calcY + 32)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.text(`${remaining} ≥ ${values[currentIndex]} → Add "${symbols[currentIndex]}", subtract ${values[currentIndex]}`);
}
// Final result
if (phase === 'done') {
svg.append("rect")
.attr("x", width / 2 - 150).attr("y", 350)
.attr("width", 300).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", 385)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`${num} = ${result}`);
}
}
function step() {
if (phase === 'done') return false;
if (currentIndex >= values.length || remaining === 0) {
phase = 'done';
document.getElementById("status").textContent = `Done! ${num} = ${result}`;
draw();
return false;
}
if (remaining >= values[currentIndex]) {
result += symbols[currentIndex];
remaining -= values[currentIndex];
document.getElementById("status").textContent =
`${remaining + values[currentIndex]} ≥ ${values[currentIndex]}: Added "${symbols[currentIndex]}", remaining = ${remaining}`;
} else {
currentIndex++;
document.getElementById("status").textContent =
`${remaining} < ${values[currentIndex - 1]}: Moving to next symbol`;
}
draw();
return currentIndex < values.length && remaining > 0;
}
function reset() {
num = parseInt(document.getElementById("numInput").value) || 1994;
remaining = num;
result = "";
currentIndex = 0;
phase = 'checking';
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to convert to Roman numeral';
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";
}
}, 600);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
document.getElementById("numInput").addEventListener("change", reset);
reset();
</script>
</body>
</html>