Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
这道题直接上来硬写的,感觉有点没动脑筋。想起当时用java课上一道关于扑克牌的课后作业,应该写的灵活些。像本题,如果还需要写出后续的数字这种写法就不妥当了。我想到的一个办法是:在个位,十位,百位使用一个for循环,因为他们的逻辑是一模一样的,除了字母不同,那么便可以用一个二位数组存好这些字母,按规则打印即可。
以下是不聪明的写法:
package leetcode;
public class Int2Roman {
// I V X L C D M
// 1 5 10 50 100 500 1000
public static void main(String[] args) {
Int2Roman int2r = new Int2Roman();
int2r.intToRoman(2500);
System.out.println();
int2r.intToRoman(735);
System.out.println();
int2r.intToRoman(14);
}
public String intToRoman(int num) {
// 1-3999
int temp = num;
int split[] = new int[4];
int point = 0;
// 反序存这个数字
while (temp > 0) {
split[point] = temp % 10;
temp = temp / 10;
point++;
}
/*
* for (int i : split) { System.out.println(i); }
*/
String res = "";
// 千位
if (split[3] != 0) {
// 如果是减法
// 如果是加法 1-3
for (int j = 0; j < split[3]; j++) {
res += "M";
}
}
//百位
if (split[2] != 0) {
// 如果是加法 1-3
if(split[2]<=3){
for (int j = 0; j < split[2]; j++) {
res += "C";
}
}
// 如果是加法 5-8
if(split[2]>=5 && split[2]<=8){
res+="D";
for(int j=split[2]-5;j>0;j--)
res+="C";
}
// 如果是减法
if(split[2]==9){
res+="CM";
}
if(split[2]==4){
res+="CD";
}
}
//十位
if (split[1] != 0) {
// 如果是减法
// 如果是加法 1-3
if(split[1]<=3){
for (int j = 0; j < split[1]; j++) {
res += "X";
}
}
// 如果是加法 5-8
if(split[1]>=5 && split[1]<=8){
res+="L";
for(int j=split[1]-5;j>0;j--)
res+="X";
}
if(split[1]==9){
res+="XC";
}
if(split[1]==4){
res+="XL";
}
}
//个位
if (split[0] != 0) {
// 如果是减法
// 如果是加法 1-3
if(split[0]<=3){
for (int j = 0; j < split[0]; j++) {
res += "I";
}
}
// 如果是加法 5-8
if(split[0]>=5 && split[0]<=8){
res+="V";
for(int j=split[0]-5;j>0;j--)
res+="I";
}
if(split[0]==9){
res+="IX";
}
if(split[0]==4){
res+="IV";
}
}
System.out.println("res:" + res);
return res;
}
}