Leetcode
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
| Symbol |
|---|
| I | V | X | L | C | D | M | |
|---|---|---|---|---|---|---|---|
| Value | 1 | 5 | 10 | 50 | 100 | 500 | 1,000 |
| Number |
|---|
| 4 | 9 | 40 | 90 | 400 | 900 | |
|---|---|---|---|---|---|---|
| Notation | IV | IX | XL | XC | CD | CM |
- So when you see M, D, L, V, don't hesitate but add the number. When you see I, X, and C, you have to check whether the number character will form a combination with it.
- Most importantly, there may not be a next character, i only guarantees s[i], not s[i+1], you need to first make sure that s[i+1] exists!!!
- When you use s[i+1], you use two characters in this loop, so i++!!!
class Solution {
public:
int romanToInt\(string s\) {
int y = 0;
for \(int i = 0; i < s.length\(\); i++\) {
switch \(s\[i\]\) {
case 'M': y += 1000; break;
case 'D': y += 500; break;
case 'L': y += 50; break;
case 'V': y += 5; break;
case 'C':
if \(i+1 >= s.length\(\)\) {
y += 100;
} else if \(s\[i+1\] == 'D'\) {
y += 400; i++;
} else if \(s\[i+1\] == 'M'\) {
y += 900; i++;
} else {
y += 100;
}
break;
case 'X':
if \(i+1 >= s.length\(\)\) {
y += 10;
} else if \(s\[i+1\] == 'L'\) {
y += 40; i++;
} else if \(s\[i+1\] == 'C'\) {
y += 90; i++;
} else {
y += 10;
}
break;
case 'I':
if \(i+1 >= s.length\(\)\) {
y += 1;
} else if \(s\[i+1\] == 'V'\) {
y += 4; i++;
} else if \(s\[i+1\] == 'X'\) {
y += 9; i++;
} else {
y += 1;
}
break;
}
}
return y;
}
};