LeetCode - The World's Leading Online Programming Learning Platform
import java.util.Enumeration;
import java.util.Hashtable;
class Solution {
public static String intToRoman(int num)
{
StringBuilder s = new StringBuilder();
Hashtable<Integer , String > list = new Hashtable<>();
list.put(1 , "I");
list.put(4 , "IV");
list.put(5 , "V");
list.put(9 , "IX");
list.put(10 , "X");
list.put(40 , "XL");
list.put(50 , "L");
list.put(90 , "XC");
list.put(100 , "C");
list.put(400 , "CD");
list.put(500 , "D");
list.put(900 , "CM");
list.put(1000 , "M");
while (num > 0)
{
int maxkey = getMaxKey(list , num);
s.append(list.get(maxkey));
num -= maxkey;
}
return s.toString();
}
public static int getMaxKey(Hashtable list , int target)
{
int maxKey = -1;
Enumeration<Integer> keys = list.keys();
while (keys.hasMoreElements()) {
int key = keys.nextElement();
if (key <= target && key > maxKey) {
maxKey = key;
}
}
return maxKey;
}
}
class Solution {
public String intToRoman(int num)
{
String ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
String tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String ths[] = {"","M","MM","MMM"};
StringBuilder ans = new StringBuilder();
ans.append(ths[num / 1000]);
ans.append(hrns[(num % 1000) / 100]);
ans.append(tens[(num % 100) / 10]);
ans.append(ones[num % 10]);
return ans.toString();
}
}