Roman To Integer [Code + Interactive Visualization]
def romanToInt(s: str) -> int:
# Handle edge cases
if not s: return -1
# Map roman numerals to values
map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
n = len(s)
# Initialize with last character's value
result = map[s[n - 1]]
# Process remaining characters right to left
for i in range(n - 2, -1, -1):
val = map[s[i]]
next = map[s[i + 1]]
if val >= next: result += val
if val < next: result -= val
return result
class Solution {
public int romanToInt(String s) {
if (s == null || s.length() == 0) return -1;
HashMap map = new HashMap();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int n = s.length();
int result = map.get(s.charAt(n - 1));
for (int i = 0; i <= n - 2; i++) {
int val = map.get(s.charAt(i));
int next = map.get(s.charAt(i + 1));
if (val >= next) result += val;
if (val < next) result -= val;
}
return result;
}
}
class Solution {
public:
int romanToInt(string s) {
// Handle edge cases
if (s.empty()) return -1;
// Map roman numerals to values
unordered_map map = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
int n = s.length();
int result = map[s[n - 1]];
// Process remaining characters right to left
for (int i = n - 2; i >= 0; i--) {
int val = map[s[i]];
int next = map[s[i + 1]];
if (val >= next) result += val;
if (val < next) result -= val;
}
return result;
}
};
Problem Statement
Given a string s containing valid Roman numerals, convert it to an integer. Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Detailed Explanation
Approach
The solution processes the Roman numeral string by comparing each character with the next one. If a smaller value precedes a larger value, we subtract it; otherwise, we add it. We start from the rightmost character and work our way left.
Key Concepts
- Roman Numeral Rules: When a smaller value appears before a larger value, it represents subtraction
- Hash Map Usage: Quick lookup of Roman numeral values
- Right to Left Processing: Compare current value with the next value to determine addition or subtraction
Algorithm Steps
- Create a hash map of Roman numeral values
- Get the value of the last character as initial result
- For remaining characters from right to left:
- Compare current value with next value
- If current ≥ next: Add current value
- If current < next: Subtract current value
- Return final result
Current Value
0
Operation
-
Result
0
Click "Next Step" to begin the visualization
Previous
Previous
H-Index [Code + Interactive Visualization]
Next
Next