您的位置:首页 > 其它

leetcode-012-Integer to Roman

2016-10-03 22:25 288 查看
P012 Integer to Roman
思路分析

代码
java

P012 Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

思路分析

这个和小学数学的考题类似了,比如问123是由几个100,几个10和几个1构成的?

关键就是找出构成数字的元数字:

二进制的元数字是0和1

十进制的元数字是0到9

罗马数字的元数字如下:

罗马字符IVXLCDM
阿拉伯数字1510501005001000
将输入数字按照这种方式拆分成几个千几个百……即可。

代码

java

public class Solution012 {

public static final String[][] base = { //
{ "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, //
{ "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, //
{ "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }, //
{ "", "M", "MM", "MMM" } //
};

public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
sb.append(base[3][(num / 1000) % 10]);
sb.append(base[2][(num / 100) % 10]);
sb.append(base[1][(num / 10) % 10]);
sb.append(base[0][(num % 10)]);
return sb.toString();
}

public static void main(String[] args) {
Solution012 s12 = new Solution012();
int xs[] = { 1, 4, 6, 7, 9, 18, 19, 99, 3999 };
for (int x : xs) {
System.out.println(x + "-->" + s12.intToRoman(x));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode roman integer