罗马数字的规则:
罗马数字采用七个罗马字母作数字:
Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。
string one[]={"I","II","III","IV","V","VI","VII","VIII","IX"};
string ten[]={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
string hundred[]={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
string thou[]={"M","MM","MMM"};
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12。
(3)小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
(4)在一个数的上面画一条横线,表示这个数增值 1,000 倍。
代码为:
//方式一
public class Solution {
public String intToRoman(int num) {
String[][] map={
{"","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"}
};
StringBuilder roman = new StringBuilder();
roman.append(map[3][num/1000%10]);
roman.append(map[2][num/100%10]);
roman.append(map[1][num/10%10]);
roman.append(map[0][num%10]);
return roman.toString();
}
}
//方式二
public String intToRoman(int num) {
int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
String[] strs = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (num >= values[i]) {
num -= values[i];
sb.append(strs[i]);
}
}
return sb.toString();
}