Convert a Roman Numeral to an Integer
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to parse string input and apply conditional arithmetic logic to convert Roman numerals into integers. It tests string traversal skills and edge-case handling of subtractive notation, commonly used to assess foundational algorithmic thinking in coding interviews.
Constraints
- 1 <= s.length <= 15
- s contains only the characters I, V, X, L, C, D, M.
- s is guaranteed to be a valid Roman numeral representing an integer in the range [1, 3999].
Examples
Input: "III"
Expected Output: 3
Explanation: Three I's, no subtraction: 1 + 1 + 1 = 3.
Input: "IV"
Expected Output: 4
Explanation: I (1) precedes V (5), so it is subtracted: 5 - 1 = 4.
Input: "IX"
Expected Output: 9
Explanation: I (1) precedes X (10), so it is subtracted: 10 - 1 = 9.
Input: "LVIII"
Expected Output: 58
Explanation: L=50, V=5, III=3, all added: 50 + 5 + 3 = 58.
Input: "MCMXCIV"
Expected Output: 1994
Explanation: M=1000, CM=900, XC=90, IV=4: 1000 + 900 + 90 + 4 = 1994.
Input: "I"
Expected Output: 1
Explanation: Single symbol edge case: I = 1.
Input: "MMMCMXCIX"
Expected Output: 3999
Explanation: Maximum valid value: MMM=3000, CM=900, XC=90, IX=9 = 3999.
Input: "XL"
Expected Output: 40
Explanation: X (10) precedes L (50), subtracted: 50 - 10 = 40.
Input: "CD"
Expected Output: 400
Explanation: C (100) precedes D (500), subtracted: 500 - 100 = 400.
Input: "MCDLXXVI"
Expected Output: 1476
Explanation: M=1000, CD=400, L=50, XX=20, V=5, I=1: 1000 + 400 + 50 + 20 + 5 + 1 = 1476.
Hints
- Map each symbol to its value. The tricky part is the six subtractive pairs (IV, IX, XL, XC, CD, CM).
- Instead of special-casing the six pairs, notice a simpler rule: scan left to right and compare each symbol with the one after it.
- If a symbol's value is less than the value of the symbol immediately to its right, subtract it; otherwise add it. This handles every subtractive case automatically.