LeetCode 12. Integer to Roman

October 28, 2024

I started feeling down about my past interview performance. Rather than continue ruminating, I decided to continue my LeetCode grind tonight. My goal is to complete the Top 150 Interview Questions before the end of the year.

Solution

1class Solution:
2 def intToRoman(self, num: int) -> str:
3 digitCount = int((math.log10(num) + 1) // 1)
4 def getLeftmostDigit():
5 return num // (10 ** (digitCount - 1)) % 10
6 romanForm = ""
7 if digitCount == 4:
8 digit = getLeftmostDigit()
9 for i in range(digit): romanForm += "M"
10 digitCount -= 1
11 if digitCount == 3:
12 digit = getLeftmostDigit()
13 if digit in [4, 9]:
14 romanForm += "CD" if digit == 4 else "CM"
15 digit -= digit
16 elif digit >= 5:
17 romanForm += "D"
18 digit -= 5
19 for i in range(digit): romanForm += "C"
20 digitCount -= 1
21 if digitCount == 2:
22 digit = getLeftmostDigit()
23 if digit in [4, 9]:
24 romanForm += "XL" if digit == 4 else "XC"
25 digit -= digit
26 elif digit >= 5:
27 romanForm += "L"
28 digit -= 5
29 for i in range(digit): romanForm += "X"
30 digitCount -= 1
31 if digitCount == 1:
32 digit = getLeftmostDigit()
33 if digit in [4, 9]:
34 romanForm += "IV" if digit == 4 else "IX"
35 digit -= digit
36 elif digit >= 5:
37 romanForm += "V"
38 digit -= 5
39 for i in range(digit): romanForm += "I"
40
41 return romanForm

O(n) = 1

Reflection

Next time, I would like to reduce the code complexity by abstracting the strings into a dictionary. With the dictionary, I could loop for digitCount iterations and select the appropriate value from the dictionary. This would remove the repeated code, thereby making it easier to read and maintain.

LeetCode 12. Integer to Roman

LeetCode 6. Zigzag Conversion