12_Integer to Roman
[medium]
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Roman rules:
M = 1000
D = 500
C = 100
L = 50
X = 10
V = 5
I = 1
Special cases to pay attention:
CM = 900
CD = 400
XC = 90
XL = 40
IX = 9
IV = 4
Idea 1
Store all Roman numerals correspond to each decimal.
Get each number for 4 decimals from input integer, convert each to Roman numerals, concatenate them together as output.
Complexity 1
Time:
Space:
Solution 1 (brute force)
Idea 2
Store all important Roman numerals, for 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1.
Loop over these important values, if num
is larger than or equal to it, add corresponding Roman letter and subtract this value. If num
is less than it, go to next value. Until num
equal to 0.
Pros and Cons
Comparing with solution 1, solution 2 doesn't need to specify all the cases. Solution 1 an solution 2 has similar running time.
Solution 2 (smart solution, less definition)
Last updated