![]() |
VOOZH | about |
Given a string s representing a Roman numeral, find it's corresponding integer value.
Roman numerals are formed using the following symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, and M = 1000.
Numbers are typically formed by combining these symbols from left to right, adding or subtracting their values based on specific rules.
How does the conversion work?
Examples:
Input: s = "IX"
Output: 9
Explanation: IX is a Roman symbol which represents 10 - 1 = 9Input: s = "XL"
Output: 40
Explanation: XL is a Roman symbol which represents 50 - 10 = 40Input: s = "MCMIV"
Output: 1904
Explanation: M is 1000, CM is 1000 - 100 = 900, and IV is 4. So we have total as 1000 + 900 + 4 = 1904
Table of Content
The idea for converting a Roman numeral to an integer is that, we have to traverse the string from left to right. For each symbol compare it with the next symbol (if it exists). If the current symbol is greater than or equal to the next symbol then add its value to the result. Otherwise, subtract its value from the next symbol's value and add the result to the total, and skip the next symbol.
9
We can use an hash map or dictionary to store the values of Roman symbols. And to solve the problem, we have to iterate through the string and for each symbol, check if the current value is less than the next value. If so, subtract the current value from the next value and add the result to the total. Otherwise, add the current value to the total.
9