-
Notifications
You must be signed in to change notification settings - Fork 20
/
IntegerToRoman.java
36 lines (33 loc) · 1.02 KB
/
IntegerToRoman.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
/**
* Given an integer, convert it to a roman numeral.
* <p>
* Input is guaranteed to be within the range from 1 to 3999.
* <p>
* Accepted.
*/
public class IntegerToRoman {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
int value[] = {1000, 500, 100, 50, 10, 5, 1};
for (int n = 0; n < 7; n += 2) {
int x = num / value[n];
if (x < 4) {
for (int i = 1; i <= x; i++) {
sb.append(roman[n]);
}
} else if (x == 4) {
sb.append(roman[n]).append(roman[n - 1]);
} else if (x < 9) {
sb.append(roman[n - 1]);
for (int i = 6; i <= x; i++) {
sb.append(roman[n]);
}
} else if (x == 9) {
sb.append(roman[n]).append(roman[n - 2]);
}
num %= value[n];
}
return sb.toString();
}
}