|
| 1 | +/** |
| 2 | + * Translates numbers into the Roman Numeral System. |
| 3 | + * |
| 4 | + * @see <a href="https://en.wikipedia.org/wiki/Roman_numerals">Roman numerals</a> |
| 5 | + * @author Sokratis Fotkatzikis |
| 6 | + * @version 1.0 |
| 7 | + */ |
| 8 | +public class RomanNumeralUtil { |
| 9 | + |
| 10 | + private static final int MIN_VALUE = 1; |
| 11 | + private static final int MAX_VALUE = 5999; |
| 12 | + //1000-5999 |
| 13 | + private static final String[] RN_M = {"", "M", "MM", "MMM", "MMMM", "MMMMM"}; |
| 14 | + //100-900 |
| 15 | + private static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; |
| 16 | + //10-90 |
| 17 | + private static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; |
| 18 | + //1-9 |
| 19 | + private static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; |
| 20 | + |
| 21 | + public static String generate(int number) { |
| 22 | + if (number < MIN_VALUE || number > MAX_VALUE) { |
| 23 | + throw new IllegalArgumentException( |
| 24 | + String.format( |
| 25 | + "The number must be in the range [%d, %d]", |
| 26 | + MIN_VALUE, |
| 27 | + MAX_VALUE |
| 28 | + ) |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + return RN_M[number / 1000] + |
| 33 | + RN_C[number % 1000 / 100] + |
| 34 | + RN_X[number % 100 / 10] + |
| 35 | + RN_I[number % 10]; |
| 36 | + } |
| 37 | +} |
0 commit comments