Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
| Symbol | Value | |--------|-------| | I | 1 | | V | 5 | | X | 10 | | L | 50 | | C | 100 | | D | 500 | | M | 1000 |
Roman numerals are usually written from largest to smallest left to right. However, there are special cases for subtraction:
I before V or X makes 4 or 9X before L or C makes 40 or 90C before D or M makes 400 or 900Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4
Key Insight: When a smaller value appears before a larger value, subtract it instead of adding it.
Algorithm:
Example: "MCMXCIV"
Time Complexity: O(n) where n is the length of the string
Space Complexity: O(1)
"MCMXCIV"
↓
M: 1000 (add, next is C which is less)
↓
C: 100 (subtract, next is M which is greater)
↓
M: 1000 (add, next is X which is less)
↓
X: 10 (subtract, next is C which is greater)
↓
C: 100 (add, next is I which is less)
↓
I: 1 (subtract, next is V which is greater)
↓
V: 5 (add, last symbol)
Result: 1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994
1/**
2 * Roman to Integer
3 * Time: O(n)
4 * Space: O(1)
5 */
6
7class Solution {
8 public int romanToInt(String s) {
9 Map<Character, Integer> values = new HashMap<>();
10 values.put('I', 1);
11 values.put('V', 5);
12 values.put('X', 10);
13 values.put('L', 50);
14 values.put('C', 100);
15 values.put('D', 500);
16 values.put('M', 1000);
17
18 int total = 0;
19 int n = s.length();
20
21 for (int i = 0; i < n; i++) {
22 int currentValue = values.get(s.charAt(i));
23
24 // If current < next, subtract it
25 if (i < n - 1 && currentValue < values.get(s.charAt(i + 1))) {
26 total -= currentValue;
27 } else {
28 total += currentValue;
29 }
30 }
31
32 return total;
33 }
34}
35