class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
numerals = {
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',
}
segment = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
res = "";
for i in segment:
temp = num / i;
res += temp * numerals[i];
num -= temp * i;
return res;
public class Solution {
public static final int[] intDict = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
public static final String[] romanDict = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
/**
* Recursion
* Go through the dict, if num >= dict, insert it to head
* Pass rest of the integer to next recursion
*/
public String intToRoman(int num) {
for (int i = 0; i < intDict.length; i++) {
if (intDict[i] <= num) {
return romanDict[i] + intToRoman(num - intDict[i]);
}
}
return ""; // Note the return statement
}
}
public class Solution {
public String intToRoman(int num) {
int[] keys = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] values = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keys.length; i++) {
while (num >= keys[i]) {
num -= keys[i];
sb.append(values[i]);
}
}
return sb.toString();
}
}