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.
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)) % 106 romanForm = ""7 if digitCount == 4:8 digit = getLeftmostDigit()9 for i in range(digit): romanForm += "M"10 digitCount -= 111 if digitCount == 3:12 digit = getLeftmostDigit()13 if digit in [4, 9]:14 romanForm += "CD" if digit == 4 else "CM"15 digit -= digit16 elif digit >= 5:17 romanForm += "D"18 digit -= 519 for i in range(digit): romanForm += "C"20 digitCount -= 121 if digitCount == 2:22 digit = getLeftmostDigit()23 if digit in [4, 9]:24 romanForm += "XL" if digit == 4 else "XC"25 digit -= digit26 elif digit >= 5:27 romanForm += "L"28 digit -= 529 for i in range(digit): romanForm += "X"30 digitCount -= 131 if digitCount == 1:32 digit = getLeftmostDigit()33 if digit in [4, 9]:34 romanForm += "IV" if digit == 4 else "IX"35 digit -= digit36 elif digit >= 5:37 romanForm += "V"38 digit -= 539 for i in range(digit): romanForm += "I"4041 return romanForm
O(n) = 1
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 74. Search a 2D Matrix
LeetCode 6. Zigzag Conversion