Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路:首先先把num按照个位十位百位千位拆分,然后对每一位上的数字按照roman to integer的对应表格,转化为对应的roman,然后就所有转化的再拼起来就是所求的结果。代码如下(已通过leetcode)
public class Solution {
public String intToRoman(int num) {
String[] str=new String[4];
String str2="";
if(num<1 || num>3999) return null;
int[] a=new int[]{0,0,0,0};
a[0]=num/1000;
if(a[0]!=0) num=num-a[0]*1000;
a[1]=num/100;
if(a[1]!=0) num=num-a[1]*100;
a[2]=num/10;
if(a[2]!=0) num=num-a[2]*10;
a[3]=num;
switch(a[3]) {
case 0: break;
case 1: str[3]="I";
break;
case 2: str[3]="II";
break;
case 3: str[3]="III";
break;
case 4: str[3]="IV";
break;
case 5: str[3]="V";
break;
case 6: str[3]="VI";
break;
case 7: str[3]="VII";
break;
case 8: str[3]="VIII";
break;
case 9: str[3]="IX";
break;
}
switch(a[2]) {
case 0: break;
case 1: str[2]="X";
break;
case 2: str[2]="XX";
break;
case 3: str[2]="XXX";
break;
case 4: str[2]="XL";
break;
case 5: str[2]="L";
break;
case 6: str[2]="LX";
break;
case 7: str[2]="LXX";
break;
case 8: str[2]="LXXX";
break;
case 9: str[2]="XC";
break;
}
switch(a[1]) {
case 0: break;
case 1: str[1]="C";
break;
case 2: str[1]="CC";
break;
case 3: str[1]="CCC";
break;
case 4: str[1]="CD";
break;
case 5: str[1]="D";
break;
case 6: str[1]="DC";
break;
case 7: str[1]="DCC";
break;
case 8: str[1]="DCCC";
break;
case 9: str[1]="CM";
break;
}
switch(a[0]) {
case 0: break;
case 1: str[0]="M";
break;
case 2: str[0]="MM";
break;
case 3: str[0]="MMM";
break;
default: break;
}
for(int i=0;i<4;i++) {
if(str[i]!=null)
str2+=str[i];
}
return str2;
}
}