All coding questions

Roman to Integer

easy
LeetCode 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)
  1. Map each Roman symbol to its integer value.
  2. Scan left to right comparing each value with the next.
  3. Subtract the current value when it is smaller than its successor, else add it.
  4. Accumulate the total.
  5. 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