package _12整数转罗马数字;
import javax.jws.soap.SOAPBinding;
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().intToRoman(2782));
}
public String intToRoman(int num) {
//存放位置
char pos[] = new char[7];
pos[0] = 'I';
pos[1] = 'V';
pos[2] = 'X';
pos[3] = 'L';
pos[4] = 'C';
pos[5] = 'D';
pos[6] = 'M';
//将每个位置对应的值
int[] value = new int[256];
value[pos[0]] = 1;
value[pos[1]] = 5;
value[pos[2]] = 10;
value[pos[3]] = 50;
value[pos[4]] = 100;
value[pos[5]] = 500;
value[pos[6]] = 1000;
int i = 0;
//寻找这个数在的区间
while (i < 7) {
if (num < value[pos[i]])
break;
i++;
}
int a = num;
String res = new String();
while (a > 0) {
//吧特殊情况单独考虑出来
if (a == 4) {
res += "IV";
break;
} else if (a == 9) {
res += "IX";
break;
} else if (a >= 40 && a < 50) {
res += "XL";
a -= 40;
} else if (a >= 90 && a < 100) {
res += "XC";
a -= 90;
} else if (a >= 400 && a < 500) {
res += "CD";
a -= 400;
} else if (a >= 900 && a < 1000) {
res += "CM";
a -= 900;
} else {
int cnt = a / value[pos[--i]];
a %= value[pos[i]];
while (cnt > 0) {
res += pos[i];
cnt--;
}
}
}
return res;
}
}
力扣第12题整数转罗马数字
最新推荐文章于 2024-03-11 16:09:52 发布