Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII.
Instead, the number four is written as IV.
Because the one is before the five we subtract it making four.
The same principle applies to the number nine, which is written as IX.
Symbol Value
I 1
V 5
X 10 L 50 C 100 D 500 M 1000
- I can be placed before V (5) and X (10) to make 4 and 9.
- X can be placed before L (50) and C (100) to make 40 and 90.
- C can be placed before D (500) and M (1000) to make 400 and 900.
로마 숫자는 I, V, X, L, C, D, M의 7가지 기호로 표현된다.
로마 숫자들은 보통 왼쪽에서 오른쪽으로 가장 큰 것부터 작은 것까지 쓰여진다.
그러나 4의 숫자는 III가 아니다. 대신 IV로 표기된다.
왜냐하면 4는 5(V)의 1(I)을 뺀 수이기 때문이다. IX로 표기된 숫자 9도 같은 원리가 적용된다.
풀이 방법
나는 뺄셈으로 처리되는 6가지 타입에 대해 먼저 처리를 진행하였다.
주어진 문자열에 6가지 타입이 포함되어있으면, 합산 후 replace 처리를 하여 해당 타입을 문자열에서 제거하였다.
남은 문자열을 한 글자씩 잘라 합산하고, 이 합산된 결과를 리턴하였다.
(메모리 효율 안습)
class Solution {
int res = 0;
public int romanToInt(String s) {
// minus object
String[] r = { "IV", "IX", "XL", "XC", "CD", "CM" };
int[] v = { 4, 9, 40, 90, 400, 900 };
for(int i=0; i<6; i++) {
s = replaceRoman(s, r[i], v[i]);
}
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(c == 'I') res += 1;
else if(c == 'V') res += 5;
else if(c == 'X') res += 10;
else if(c == 'L') res += 50;
else if(c == 'C') res += 100;
else if(c == 'D') res += 500;
else if(c == 'M') res += 1000;
}
return res;
}
public String replaceRoman(String s, String keyword, int val) {
while(s.indexOf(keyword) != -1) {
res += val;
s = s.replace(keyword, "");
}
return s;
}
}