The following code only converts the integers to numerals up to 1010. At that point, an error starts to occur.
class Solution:
def intToRoman(self, num: int) -> str:
numerals = {
1: "I",
4: "IV",
5: "V",
10: "X",
40: "XL",
50: "L",
90: "XC",
100: "C",
400: "CD",
500: "D",
900: "CM",
1000: "M"
}
output = ""
for k,v in sorted(numerals.items(), reverse=True):
while num >= k:
output += v
num -= k
return output
I am looping through the numerals
dictionary from greatest to least number wise and getting the ints (v) and the numerals (k)
Then I am using a while loop to see if the number is >= value (v)
After that output will be added to the numerals (k), and number (num) will be subtracted from the integer (v).
Then I return value.
I was thinking of doing something like an if statement maybe like:
if num < v:
# code
Whenever I try adding that, I get a "Time Limit Exceeded"