十进制数转罗马数字 - Switch笨方法解题
程序员文章站
2022-05-18 10:17:39
...
数字转罗马数字工具类
class NumberChange {
public static String reverseStr(String str) {
StringBuilder sb = new StringBuilder();
int index = str.length() - 1;
for (int i = index; i >= 0; i--) {
sb.append(str.substring(i, i + 1));
}
return sb.toString();
}
public static String currentLocationInvert( String number , Integer zeroCount) {
Integer num = Integer.parseInt(number);
StringBuilder sb = new StringBuilder();
switch(zeroCount) {
case 0 : {
if(num<4) {
for(int i = 0; i < num; i++) {
sb.append("I");
}
}else if(num == 4) {
sb.append("IV");
}else if(num == 5) {
sb.append("V");
}else if(num == 9) {
sb.append("IX");
}else {
sb.append("V");
for(int i = 0; i<num-5; i++) {
sb.append("I");
}
}
break;
}
case 1 : {
if(num<4) {
for(int i = 0; i < num; i++) {
sb.append("X");
}
}else if(num == 4) {
sb.append("XL");
}else if(num == 5) {
sb.append("L");
}else if(num == 9) {
sb.append("XC");
}else {
sb.append("L");
for(int i = 0; i<num-5; i++) {
sb.append("X");
}
}
break;
}
case 2 : {
if(num<4) {
for(int i = 0; i < num; i++) {
sb.append("C");
}
}else if(num == 4) {
sb.append("CD");
}else if(num == 5) {
sb.append("D");
}else if(num == 9) {
sb.append("CM");
}else {
sb.append("D");
for(int i = 0; i<num-5; i++) {
sb.append("C");
}
}
break;
}
case 3 : {
for(int i = 0; i < num; i++) {
sb.append("M");
}
}
}
return sb.toString();
}
public static String invertToRoman(Integer number) {
// 1. 只转 1-3999范围的数字
if(number<1 || number > 3999) {
throw new RuntimeException("请输入在【1~3999】范围内的数字 - 小老弟别搞事");
}
// 2. 将数字倒序
String strNum = reverseStr(number.toString());
// 3. 定义一个字符输出对象
StringBuilder sb = new StringBuilder();
// 4. 遍历输出 - 打印
for(int i = strNum.length()-1; i>=0; i--) {
String num = strNum.substring(i,i+1);
String roma = currentLocationInvert(num, i);
sb.append(roma);
}
// 5. 返回结果
return sb.toString();
}
}
测试代码
public static void main(String[] args) {
System.out.println(NumberChange.invertToRoman(1994));
System.out.println(NumberChange.invertToRoman(58));
System.out.println(NumberChange.invertToRoman(9));
System.out.println(NumberChange.invertToRoman(4));
System.out.println(NumberChange.invertToRoman(3));
}
输出结果
看了这篇推文解题,我不禁发出一句卧槽,居然还能那么简单
https://www.cnblogs.com/mxwbq/p/10956786.html