math
string
]
Leetcode 0012. Integer to Roman
https://leetcode.com/problems/integer-to-roman
Let us look at Roman representation digit by digit and see how it works.
For last digit we can have
" ", I, II, III, IV, V, VI, VII, VIII, IX
For next digit we can have
" ", X, XX, XXX, XL, L, LX, LXX, LXXX, XC
and so on.
Notice, that we have exactly the same pattern here, but instead of I, V, X
, we have X, L, C
symbols. Let us use this idea and function digit
to construct our number. We find last digit of integer representation of our number, create corresponding roman part and add it to the beginning of our answer.
Complexity: time complexity is just O(1)
, because length is restricted by 15
. Space complexity is O(1)
as well.
class Solution:
def intToRoman(self, num):
def digit(a,b,c,dig):
return ["",a,2*a,3*a,a+b,b,b+a,b+2*a,b+3*a,a+c][dig]
l = ["I","V","X","L","C","D","M","!","!"]
out, i = "", 0
while num != 0:
num, last = divmod(num, 10)
out = digit(l[i], l[i+1], l[i+2], last) + out
i += 2
return out
If you like the solution, you can upvote it on leetcode discussion section: Problem 0012