12. Integer to Roman
Previous395. Longest Substring with At Least K Repeating CharactersNext807. Max Increase to Keep City Skyline
Last updated
Last updated
Input: 4
Output: "IV"Input: 9
Output: "IX"Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.class Solution {
public String intToRoman(int num) {
String[] str = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int[] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
StringBuilder res = new StringBuilder();
int i = 0;
while(num > 0){
while(num >= value[i]){
num -= value[i];
res.append(str[i]);
}
i++;
}
return res.toString();
}
}class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
romanDict = {1:'I',4:'IV',5:'V',9:'IX',10:'X',40:'XL',50:'L',
90:'XC',100:'C',400:'CD',500:'D',900:'CM',1000:'M'}
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ]
res = ""
i = 0
while num > 0:
while num >= values[i]:
num -= values[i]
res += romanDict[values[i]]
i+=1
return res