Roman to Integer
easyLeetCode Top 100mathstringshashing
Problem
Given a Roman numeral string, convert it to its integer value. A smaller numeral placed before a larger one is subtracted rather than added.
Examples
Input: s = "III"
Output: 3
Three ones.
Input: s = "MCMXCIV"
Output: 1994
1000 + (1000-100) + (100-10) + (5-1).
Constraints
- • 1 <= s.length <= 15
- • Input is a valid Roman numeral within 1 to 3999
Hints(tap to reveal)
- 1. Map each symbol to its value.
- 2. Subtract when a symbol is smaller than the one after it.
Optimal approach(spoiler)
- Map each Roman symbol to its integer value.
- Scan left to right comparing each value with the next.
- Subtract the current value when it is smaller than its successor, else add it.
- Accumulate the total.
- O(n) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor