您的位置:首页 > 其它

[LeetCode]12 Integer to Roman

2015-01-02 13:19 489 查看
https://oj.leetcode.com/problems/integer-to-roman/
http://fisherlei.blogspot.com/2012/12/leetcode-integer-to-roman.html
public class Solution {

//
// 把4,9 定义为特殊的字符
// 从大到小适配
public String intToRoman(int num) {
if (num < 1 || num > 3999)
return null; // Invalid input.

StringBuilder sb = new StringBuilder();
while (num > 0)
{
for (int i : list)
{
if (num >= i)
{
sb.append(map.get(i));
num -= i;
break;
}
}
}
return sb.toString();
}

private static final String ONE = "I";
private static final String FIVE = "V";
private static final String TEN = "X";
private static final String FIFTY = "L";
private static final String HUNDRED = "C";
private static final String FIVE_HUNDREDS = "D";
private static final String THOUSAND = "M";

private static final Map<Integer, String> map = new HashMap<>();
private static final List<Integer> list = new ArrayList<>();
static
{
// Make it unmodifiable
map.put(1000, "M");
map.put(900, "CM");
map.put(500, "D");
map.put(400, "CD");
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");

list.add(1000);
list.add(900);
list.add(500);
list.add(400);
list.add(100);
list.add(90);
list.add(50);
list.add(40);
list.add(10);
list.add(9);
list.add(5);
list.add(4);
list.add(1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode