The Roman to integer problem deals with converting a Roman numeral to its decimal value equivalent.
Roman numerals have seven symbols. The table below shows these symbols and their decimal equivalents:
Symbol | Value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
Numbers are formed by combining symbols and adding their respective values. Roman numerals are usually written from largest to smallest, and from left to right. However, the numeral for four is not IIII; instead, it is written as IV. When there is a smaller number placed before a larger number, the values are subtracted; because the one is placed before the five, we can subtract it to get four. The same principle applies to the number nine, which is written as IX.
Loop through each character in the string containing the roman numerals.
Compare the value of the current roman symbol with the value of the roman symbol to its right.
The following codes implement the algorithm above:
#include <iostream>#include <map>using namespace std;int romanToInt(string s) {map<char, int> values = {{'I', 1}, {'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500},{'M', 1000}};int total = 0;for(int i = 0; i < s.length(); i++){// If the current value is greater than or equal// to the value of the symbol to the rightif(values[s[i]] >= values[s[i+1]]){total = total + values[s[i]];}// If the current value is smaller than// the value of the symbol to the rightelse{total = total - values[s[i]];}}return total;}int main() {// Driver codestring inputString = "MCMXCIV";cout<<romanToInt(inputString)<<endl;return 0;}
Free Resources