JavaAlgorithms/Conversions/IntegerToRoman.java

40 lines
1.0 KiB
Java
Raw Normal View History

2019-06-16 01:52:14 +08:00
package Conversions;
2019-12-11 12:35:54 +08:00
/**
* Converting Integers into Roman Numerals
*
2021-10-01 13:08:17 +08:00
* <p>('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50); ('XC',90); ('C', 100);
2020-10-24 18:23:28 +08:00
* ('D', 500); ('M', 1000);
2019-12-11 12:35:54 +08:00
*/
2019-06-16 01:52:14 +08:00
public class IntegerToRoman {
2020-10-24 18:23:28 +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-12-11 12:35:54 +08:00
2020-10-24 18:23:28 +08:00
// Value must be > 0
2019-06-20 17:23:49 +08:00
2020-10-24 18:23:28 +08:00
public static String integerToRoman(int num) {
if (num <= 0) {
return "";
}
2019-06-20 17:23:49 +08:00
2020-10-24 18:23:28 +08:00
StringBuilder builder = new StringBuilder();
2019-06-20 17:23:49 +08:00
2020-10-24 18:23:28 +08:00
for (int a = 0; a < allArabianRomanNumbers.length; a++) {
int times = num / allArabianRomanNumbers[a];
for (int b = 0; b < times; b++) {
builder.append(allRomanNumbers[a]);
}
2019-06-20 17:23:49 +08:00
2020-10-24 18:23:28 +08:00
num -= times * allArabianRomanNumbers[a];
2019-06-16 01:52:14 +08:00
}
2019-06-20 17:23:49 +08:00
2020-10-24 18:23:28 +08:00
return builder.toString();
}
public static void main(String[] args) {
System.out.println(IntegerToRoman.integerToRoman(2131));
}
2019-06-16 01:52:14 +08:00
}