如题
首先想到的是通过进制位去匹配
public static String change(int num) {
StringBuilder sb = new StringBuilder("");
int a = num / 1000;
int b = num % 1000;
int c = num % 100;
int d = num % 10;
for (int i = 0; i < a; i++) {// 千位处理
sb.append("M");
}
for (int i = b / 100; i > 0; i--) {// 百位处理
if (i==9) {
sb.append("CM");
i-=9;
}else if(i >= 5) {
sb.append("D");
i -= 4;
} else if (i == 4) {
sb.append("CD");
i -= 4;
} else {
sb.append("C");
}
}
for (int i = c / 10; i > 0; i--) {// 十位处理
if (i==9) {
sb.append("XC");
i-=9;
}else if(i >= 5) {
sb.append("L");
i -= 4;
} else if (i == 4) {
sb.append("XL");
i -= 4;
} else {
sb.append("X");
}
}
for (int i = d; i > 0; i--) {// 个位处理
if (i==9) {
sb.append("IX");
i-=9;
}else if(i >= 5) {
sb.append("V");
i -= 4;
} else if (i == 4) {
sb.append("IV");
i -= 4;
} else {
sb.append("I");
}
}
return sb.toString();
}
很笨的方法
换一种思路,不拘泥于进制了,通过分解因式来做
public static String change1(int num) {
StringBuilder sb =new StringBuilder("");
int [] is = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String []ss= {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};![在这里插入图片描述](https://img-blog.csdnimg.cn/20200528183005641.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIzMTM0MDM5,size_16,color_FFFFFF,t_70)
int i =0;
while(num!=0) {
if(num>=is[i]) {
num-=is[i];
sb.append(ss[i]);
}else {
i++;
}
}
return sb.toString();
}
灵活很多了就