Leetcode - Integer to Roman (Python)

preview_player
Показать описание
March 2021 Leetcode Challenge
Leetcode - Integer to Roman #12
Difficulty: Medium
Рекомендации по теме
Комментарии
Автор

hahaha loved the last quote "do not trust me, i know nothing" 😂 after solving the problem

israellopez
Автор

I think all solutions to this are O(1) since the set of all roman numerals is constant - fixed rather. That's the argument I was seeing on discussion boards.

class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
numbers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
letters = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']

output = ""
start = len(numbers)-1
while num > 0:
while num // numbers[start] >= 1:
output += letters[start]
num -= numbers[start]
start -= 1
return output

janmichaelaustria
Автор

I did somewhat similar:

def intToRoman(self, num: int) -> str:
ans=[]
roman = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'}
for k, v in roman.items():
ans.append(num//k*v)
num%=k
return "".join(ans)
also I would argue that time is O(1) as there is a finite set of Roman numerals therefore Space is also constant

VladBurlutsky
Автор

Hi Tim I have a coming interview with FB, what do you recommend me to study? Which algo? This is for DE not SWE. Thanks and congrats on your channel

toniomz
Автор

when i run the program it says "def intToRoman(self, num: int) -> str:" has a syntax error. any idea why?

bradendavis
Автор

Hey Tim, isn't this cheating tho. I couldn't figure out a way to solve it without keeping all the possible Roman numerals in the lookup either.

My binary search solution. I think it is faster for the case if the number is 1001.

class Solution:
def intToRoman(self, num: int) -> str:
values = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
numerals = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']

number=""
idx=-1
while num!=0:
if num >= values[idx]:
number+=numerals[idx]
num-=values[idx]
else:
idx=bisect.bisect(values, num, hi=idx)-1

return number

CEOofTheHood
Автор

Hey, Great video, +sub and like, for noob for me it would be great if u explained the details a bit more while writing the code.

sinnyman