Symbol | Value | Symbol | Value | Symbol | Value |
---|---|---|---|---|---|
I | 1 | L | 50 | D | 500 |
V | 5 | C | 100 | M | 1000 |
X | 10 |
For example,
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.
There are six instances where subtraction is used:
Given a roman numeral, convert it to an integer.
Example 1:
Example 2:
Example 3:
Constraints:
Check if next value is greater than previous than subtract it from next value and add it to result.
Otherwise simply add current value to result.
class Solution {
public int romanToInt(String s) {
int num = 0;
for (int i = 0; i < s.length(); i++) {
int val1 = value(s.charAt(i));
if (i + 1 < s.length()) {
int val2 = value(s.charAt(i + 1));
if (val1 < val2) {
num += val2 - val1;
i++;
} else {
num += val1;
}
} else {
// last index
num += val1;
}
}
return num;
}
public int value(char roman) {
switch (roman) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
default:
return 1000;
}
}
}