Problems

Roman to Integer

easy
easy
strings
math
hashmap

Convert a valid canonical Roman numeral to an integer. A smaller symbol before a larger symbol is subtractive; otherwise values are added.

Input / output

  • Input: s: string
  • Output: integer value

Examples

  1. "III" returns 3.
  2. "MCMXCVI" returns 1996.

Constraints

  • 1 <= s.length <= 15
  • s is a valid uppercase canonical Roman numeral representing 1..3999.

Follow-up Can you express the conversion as a single left-to-right pass without special-casing each subtractive pair?

Examples

Example 1

Input: s = "III"
Output: 3

Example 2

Input: s = "IV"
Output: 4

Example 3

Input: s = "MCMXCVI"
Output: 1996
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.