-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathRomanNumeralUtil.java
73 lines (69 loc) · 1.49 KB
/
RomanNumeralUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.maths;
/**
* Translates numbers into the Roman Numeral System.
*
* @see <a href="https://en.wikipedia.org/wiki/Roman_numerals">Roman
* numerals</a>
* @author Sokratis Fotkatzikis
* @version 1.0
*/
public final class RomanNumeralUtil {
private RomanNumeralUtil() {
}
private static final int MIN_VALUE = 1;
private static final int MAX_VALUE = 5999;
// 1000-5999
private static final String[] RN_M = {
"",
"M",
"MM",
"MMM",
"MMMM",
"MMMMM",
};
// 100-900
private static final String[] RN_C = {
"",
"C",
"CC",
"CCC",
"CD",
"D",
"DC",
"DCC",
"DCCC",
"CM",
};
// 10-90
private static final String[] RN_X = {
"",
"X",
"XX",
"XXX",
"XL",
"L",
"LX",
"LXX",
"LXXX",
"XC",
};
// 1-9
private static final String[] RN_I = {
"",
"I",
"II",
"III",
"IV",
"V",
"VI",
"VII",
"VIII",
"IX",
};
public static String generate(int number) {
if (number < MIN_VALUE || number > MAX_VALUE) {
throw new IllegalArgumentException(String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE));
}
return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] + RN_I[number % 10]);
}
}