Roman to Integer – Solution & Complexity
Watch: Roman to Integer in one pass
Add each symbol's value, except when a smaller symbol comes before a larger one, as in IV or CM; then subtract it. One left-to-right pass with a lookup table: O(n) time.
Solution Walkthrough
Step 1: Understanding the Problem
- You are given a Roman numeral, and you need to convert it to an integer.
- Roman numerals are made up of symbols (
I,V,X,L,C,D,M) with respective values. - The numeral can range from 1 to 3999, and subtraction cases (like
IVfor 4) must be handled.
Step 2: List Roman Numerals and Values
- Roman numerals are represented by seven different symbols with specific values:
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000- Subtraction cases include:
- I before V (5) and X (10) to make 4 and 9.
- X before L (50) and C (100) to make 40 and 90.
- C before D (500) and M (1000) to make 400 and 900.
Step 3: Create a Mapping for Roman Numerals
- Use a dictionary to map Roman numeral symbols to their corresponding integer values.
- This will allow for constant-time lookups during conversion.
Step 4: Iterate Through the String
- To process the Roman numeral, iterate through the string from left to right.
- For each character, look up its corresponding value using the dictionary.
Step 5: Handle Subtraction Cases
- Roman numerals use subtraction in specific cases (like
IV= 4). - If a smaller value comes before a larger one, subtract the smaller value instead of adding it.
- Roman numerals use subtraction in specific cases (like
Step 6: Return the Final Sum
- After processing all characters in the Roman numeral string, return the accumulated total value, which represents the integer conversion.
Step 7: Handle Edge Cases
- Make sure that input Roman numerals are valid and within the range (1-3999).
- Since the problem guarantees this, we don't need extra validation, but this could be added in a more general implementation.