/
Solution.java
executable file
·77 lines (60 loc) · 2 KB
/
Solution.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
74
75
76
77
public class Solution {
public String intToRoman(int num) {
String[] symbol = {"M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"};
int[] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String res = "";
for(int i = 0; i< value.length; i++){
while(num >= value[i]){
res += symbol[i];
num -= value[i];
}
}
return res;
}
}
public class Solution {
/*
http://en.wikipedia.org/wiki/Roman_numerals
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
to avoid four characters being repeated in succession
*/
static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 };
static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' };
public String intToRoman(int num) {
String buff = "";
char last = 0;
int samecount = 0;
while (num > 0){
for(int i = N.length - 1; i >= 0; i--){
if(num >= N[i]){
num -= N[i];
buff += C[i];
if(last == C[i]){
samecount++;
}else{
samecount = 0;
}
if(samecount == 3){
int s = 5 * N[i];
buff = buff.substring(0, buff.length() - 4);
if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){
s += N[i + 1];
buff = buff.substring(0, buff.length() - 1);
}
return buff + C[i] + intToRoman(s) + intToRoman(num);
}
last = C[i];
break;
}
}
}
return buff;
}
}