The Roman to integer problem

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.

1 of 3

Algorithm

  • 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.

    1. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total.
    2. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total.

Code

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 right
if(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 right
else{
total = total - values[s[i]];
}
}
return total;
}
int main() {
// Driver code
string inputString = "MCMXCIV";
cout<<romanToInt(inputString)<<endl;
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved