这个题还是很有意思的,现代数字转罗马数字,还算有些实际用处的题。
来看看我的解法:
class Solution {
public static String intToRoman(int num) {
if(num < 0 || num>3999) return null;
char[] romaA = {
' ','I','V','X','L','C','D','M'};
//{ 1 , 5 , 10, 50,100,500,1000}
String[] romaB= {
" ","XL","XC","CD","CM"};
// { 40 , 90 , 400, 900 }
//I可以放在V或X的左边,来表示4和9
//X可以放在L和C的左边表示40和90
//C可以放在D和M的左边,表示400和900
//输入在1-3999的范围内
StringBuilder strbu= new StringBuilder(10);
int remainder = 0;
int sign = 1;
while(num!=0) {
remainder = num % 10;
num = num / 10;
if(sign==1) {
strbu.append(getRoma(remainder));
}
else if(sign==2) {
if(remainder<=3) {
strbu.insert(0, getX(remainder));
}else if(remainder==4) {
strbu.insert(0, romaB[1]);
}else if(remainder==5) {
strbu.insert(0, romaA[4]);
}else if(remainder<9) {
strbu.insert(0, "L"+getX(remainder-5));
}else if(remainder==9) {
strbu.insert(0, romaB[2]);
}
}
else if(sign==3) {
if(remainder<=3) {
strbu.insert(0, getC(remainder));
}else if(remainder==4) {
strbu.insert(0, romaB[3]);
}else if(remainder==5) {
strbu.insert(0, romaA[6]);
}else if(remainder<9) {
strbu.insert(0, romaA[6]+getC(remainder-5));
}else if(remainder==9) {
strbu.insert(0, romaB[4]);
}
}
else if(sign==4) {
strbu.insert(0, getM(remainder));
}
sign++;
}
//用例 3999MMMCMXCIX 444CDXLIV
return strbu.toString();
}
public static String getRoma(int num) {
String[] roma = {
"","I","II","III","IV","V","VI","VII","VIII","IX","X"};
return roma[num];
}
public static String getX(int num) {
String info = "";
while(num!=0) {
info+="X";
num--;
}
return info;
}
public static String getC(int num) {
String info = "";
while(num!=0) {
info+="C";
num--;
}
return info;
}
public static String getM(int num) {
String info = "";
while(num!=0) {
info+="M";
num--;
}
return info;
}
}