로마자 표기를 10진수 값으로 리턴하기.
https://leetcode.com/problems/roman-to-integer/
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.1. Constraints
- IV: 4
- IX: 9
- XL: 40
- XC: 90
- CD: 400
- CM: 900
2. Ideas
- calculate linear ch by ch, but some char(I,X,C) check next char. -> O(N)
3. Test Cases
- assert(romanToInt("LVIII") == 58)
- assert(romanToInt("IV") == 4)
- assert(romanToInt("VIII") == 8)
- assert(romanToInt("IX") == 9)
4. Coding
int romanToInt(char * s){
int ssize = strlen(s);
int ret = 0;
for (int i = 0; i < ssize; i++) {
switch (s[i]) {
case 'I':
if (i + 1 < ssize && s[i + 1] == 'V') {
ret += 4;
i++;
continue;
}
if (i + 1 < ssize && s[i + 1] == 'X') {
ret += 9;
i++;
continue;
}
ret += 1;
break;
case 'V':
ret += 5;
break;
case 'X':
if (i + 1 < ssize && s[i + 1] == 'L') {
ret += 40;
i++;
continue;
}
if (i + 1 < ssize && s[i + 1] == 'C') {
ret += 90;
i++;
continue;
}
ret += 10;
break;
case 'L':
ret += 50;
break;
case 'C':
if (i + 1 < ssize && s[i + 1] == 'D') {
ret += 400;
i++;
continue;
}
if (i + 1 < ssize && s[i + 1] == 'M') {
ret += 900;
i++;
continue;
}
ret += 100;
break;
case 'D':
ret += 500;
break;
case 'M':
ret += 1000;
break;
}
}
return ret;
}