一 题目描述
罗马数字包含以下七种字符: I
, V
, X
, L
,C
,D
和 M
。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II
,即为两个并列的 1。12 写做 XII
,即为 X
+ II
。 27 写做 XXVII
, 即为 XX
+ V
+ II
。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII
,而是 IV
。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX
。这个特殊的规则只适用于以下六种情况:
I
可以放在V
(5) 和X
(10) 的左边,来表示 4 和 9。X
可以放在L
(50) 和C
(100) 的左边,来表示 40 和 90。C
可以放在D
(500) 和M
(1000) 的左边,来表示 400 和 900。
给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
示例 1:
输入: 3
输出: "III"
示例 2:
输入: 4
输出: "IV"
示例 3:
输入: 9
输出: "IX"
示例 4:
输入: 58
输出: "LVIII"
解释: C = 100, L = 50, XXX = 30, III = 3.
示例 5:
输入: 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.
二 解题思路
1.构建一个整数组,从大到小存放每一个罗马数字所代表的数值,再构建一个字符数组,其每个位置存放与整数相对应的索引所对应的罗马字符
2.将传进来的数值与整数数组首索引进行对比,如果大于或者等于,则将该所对应的罗马数值添加进一个StringBuffer对象中,且将传进来的数值减去所对比数值,否则所对比的索引加1,依次类推,直到num减为0
三 代码实战
public static String newIntToRoman(int num){
int [] value = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String [] key = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuffer s = new StringBuffer();
int index=0;
while(num>0){
if(num>=value[index]){
s.append(key[index]);
num-=value[index];
}else {
index++;
}
}
return s.toString();
}
四 旧思路对比
之前我是从数字的尾部开始遍历对每一个值所对应的罗马数字进行判断,多了很多比较,所过单元测试执行的时间是123ms,代码如下:
public static String intToRoman(int num) {
String s = "";
int count = 0;
while (num != 0) {
int unitNum = num % 10;
if (unitNum > 0 && unitNum < 4) {
s = addSameChar(selectRomanByInt(unitNum,count),unitNum) +s;
}else if(unitNum>5&&unitNum<9){
unitNum-=5;
s = selectRomanByInt(5,count)+addSameChar(selectRomanByInt(unitNum,count),unitNum)+s;
}else {
s = selectRomanByInt(unitNum,count)+s;
}
count++;
// unitNum =num%10;
System.out.println("num:"+num);
System.out.println("count:"+count);
System.out.println("unitNum:"+unitNum);
System.out.println("s:"+s);
num/=10;
}
return s;
}
public static String addSameChar(String str,int num){
String s = "";
for (int i=0;i<num;i++){
s+=str;
}
return s;
}
public static String selectRomanByInt(int num,int count){
String s = "";
if(count==0) {
if(num==4) {
s = "IV";
}else if(num==5) {
s = "V";
}else if(num==9){
s = "IX";
}else if(num==0){
return s;
}
else {
s = "I";
}
}else if(count ==1){
if(num ==4){
s = "XL";
}else if(num ==5){
s = "L";
}else if(num==9){
s = "XC";
}else if(num==0){
return s;
}
else {
s = "X";
}
}else if(count ==2) {
if(num ==4){
s = "CD";
}else if(num ==5){
s = "D";
}else if(num==9){
s = "CM";
}else if(num==0){
return s;
}
else {
s = "C";
}
}else {
s = "M";
}
return s;
}