JavaAlgorithms/Conversions/IntegerToRoman.java

30 lines
923 B
Java
Raw Normal View History

2019-06-16 01:52:14 +08:00
package Conversions;
public class IntegerToRoman {
2019-06-20 17:23:49 +08:00
private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
2019-06-16 01:52:14 +08:00
public static String integerToRoman(int num) {
2019-06-20 17:23:49 +08:00
if (num <= 0) {
return "";
}
StringBuilder builder = new StringBuilder();
for (int a = 0; a < allArabianRomanNumbers.length; a++) {
int times = num / allArabianRomanNumbers[a];
for (int b = 0; b < times; b++) {
builder.append(allRomanNumbers[a]);
}
num -= times * allArabianRomanNumbers[a];
}
return builder.toString();
2019-06-16 01:52:14 +08:00
}
2019-06-20 17:23:49 +08:00
2019-06-16 01:52:14 +08:00
public static void main(String[] args) {
2019-06-20 17:23:49 +08:00
System.out.println(IntegerToRoman.integerToRoman(2131));
}
2019-06-16 01:52:14 +08:00
}