The task is to convert a given Roman numeral (represented as a string) to its corresponding integer value. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. Below is a table of these symbols with their values:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Roman numerals are usually written from largest to smallest from left to right. However, there are exceptions where a smaller numeral precedes a larger numeral, indicating subtraction. Examples of such combinations include IV (4) and IX (9).
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int romanToInt(string s) {
unordered_map<char, int> roman = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
int total = 0;
for (size_t i = 0; i < s.length(); ++i) {
if (i < s.length() - 1 && roman[s[i]] < roman[s[i + 1]]) {
total -= roman[s[i]];
} else {
total += roman[s[i]];
}
}
return total;
}
// Test function
int main() {
string roman = "MCMXCIV"; // 1994
cout << "Integer value of Roman numeral " << roman << " is " << romanToInt(roman) << endl;
return 0;
}
The time complexity of the solution is O(n), where n
is the length of the input string. This is because each character in the string is checked once.
This method ensures the Roman numeral string is efficiently converted to the integer value correctly based on Roman numeral rules.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?