题解(对官方题解的学习):
import java.util.Scanner;
public class Main2 {
static int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static String[] symbols = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
public static String intToRoman(int num) {
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < values.length; i++) {
int value = values[i];
String symbol = symbols[i];
while (num >= value) {
num -= value;
sbf.append(symbol);
}
if (num == 0) {
break;
}
}
System.out.println(sbf.toString());
return sbf.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
intToRoman(i);
}
}
|