Convert a Roman Numeral to an Integer
AppleSoftware Engineer · OnsiteLast updated
This problem tests your ability to parse string-based symbols while applying conditional arithmetic logic to handle additive and subtractive Roman numeral rules.
Problem Statement
Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M with corresponding values 1, 5, 10, 50, 100, 500, and 1000.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a string s containing a Roman numeral, return its integer equivalent.
Function Signature
def romanToInt(s: str) -> int:
Examples
Example 1:
Input: s = "III"
Output: 3
Explanation: I + I + I = 3.
Example 2:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4. 1000 + 900 + 90 + 4 = 1994.
Constraints
1 <= s.length <= 15scontains only the characters('I', 'V', 'X', 'L', 'C', 'D', 'M').- It is guaranteed that
sis a valid Roman numeral in the range[1, 3999].
Hints
Hint 1
Consider creating a mapping dictionary to store the integer value of each Roman numeral symbol.
Hint 2
Traverse the string from left to right; if the current value is less than the value of the next character, you must subtract the current value instead of adding it.
Hint 3
Alternatively, you can iterate from right to left, keeping track of the previous value to determine if the current character should be added or subtracted.
Follow-up questions
- How would you modify your solution to validate whether a given string is a correctly formed Roman numeral?
- What changes would be required to support an integer-to-Roman numeral conversion function?
- If the input string were extremely large (hypothetically millions of characters), how would you optimize the memory usage of your approach?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.