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"
I'm not sure what you're seeing. When I fix your typos, this code produces good results.
However, in the interest of micro-optimization, I've replaced your unnecessary dictionary with a tuple that is already in order:
class Solution:
numerals = (
("M", 1000),
("CM", 900),
("D", 500),
("CD", 400),
("C", 100),
("XC", 90),
("L", 50),
("XL", 40),
("X", 10),
("IX", 9),
("V", 5),
("IV", 4),
("I", 1),
)
def intToRoman(self, num: int) -> str:
output = ""
for k,v in self.numerals:
while num >= v:
output += k
num -= v
return output
s = Solution()
print( s.intToRoman( 10 ) )
print( s.intToRoman( 19 ) )
print( s.intToRoman( 4345 ) )
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments