public class RomaNum {
private char[] signs = {
'I', 'V', 'X', 'L', 'C', 'D', 'M'
};
private int[] values = {
1, 5, 10, 50, 100, 500, 1000
};
public String toRomaNum(int digitNum) {
StringBuilder sb = new StringBuilder();
String s = Integer.toString(digitNum);
for (int i = 0; i < s.length(); i++) {
int d = s.length() - i - 1;
char ch = s.charAt(i);
switch (ch) {
case '1':
sb.append(signs[d * 2]);
break;
case '2':
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
break;
case '3':
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
break;
case '4':
sb.append(signs[d * 2]);
sb.append(signs[d * 2 + 1]);
break;
case '5':
sb.append(signs[d * 2 + 1]);
break;
case '6':
sb.append(signs[d * 2 + 1]);
sb.append(signs[d * 2]);
break;
case '7':
sb.append(signs[d * 2 + 1]);
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
case '8':
sb.append(signs[d * 2 + 1]);
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
sb.append(signs[d * 2]);
case '9':
sb.append(signs[d * 2]);
sb.append(signs[d * 2 + 2]);
break;
default:
break;
}
}
return sb.toString();
}
public int toDigitNum(String romaNum) {
int[] n = new int[romaNum.length() * 3];
int sum = 0;
for (int i = 0; i < romaNum.length(); i++) {
char sign = romaNum.charAt(i);
for (int j = 0; j < signs.length; j++) {
if (sign == signs[j]) {
n[i] = values[j];
break;
}
}
}
for (int i = 1; i < n.length; i++) {
if (n[i - 1] < n[i]) {
sum += n[i] - n[i - 1];
i++;
} else {
sum += n[i - 1];
}
}
return sum;
}
public static void main(String[] args) {
RomaNum rn = new RomaNum();
System.out.println(rn.toRomaNum(2493));
System.out.println(rn.toDigitNum("MMMCCCXXXIII"));
}
}