-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntegerToRoman.java
38 lines (36 loc) · 996 Bytes
/
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
37
38
public class Solution {
static final char[][] table = {
{'I', 'V', 'X'},
{'X', 'L', 'C'},
{'C', 'D', 'M'},
{'M', '-', '-'},
};
public String intToRoman(int num) {
StringBuffer sb = new StringBuffer();
intToRoman(num, 0, sb);
return sb.toString();
}
private void intToRoman(int num, int idx, StringBuffer sb) {
if (num <= 0)
return;
if (num >= 10)
intToRoman(num / 10, idx + 1, sb);
int digit = num % 10;
if (digit == 9) {
sb.append(table[idx][0]);
sb.append(table[idx][2]);
}
else if (digit == 4) {
sb.append(table[idx][0]);
sb.append(table[idx][1]);
}
else {
if (digit >= 5) {
sb.append(table[idx][1]);
digit -= 5;
}
for (int i = 0; i < digit; i++)
sb.append(table[idx][0]);
}
}
}