Converting Roman Numerals to Decimal In C++
Convert Roman Numerals to Decimal
Today in this article we will be discussing how to Convert Roman Numerals to Decimal.
Lets understand this with the help of example :-
- Input:- IX
Output:- 9
IX is a Roman symbol which represents 9

Algorithm
- First we’ll take an unordered_map that will map the character to the corresponding numerical value .
- Will iterate from right to left throughout the string starting from i = size()-2 to i>=0;
- After that we will check if the mp[s[i]]<mp[s[i+1]] if this is true then will decrement the value of mp[ s[i]] from ans
- Otherwise we will add the value of mp[ s[i]] in ans
- Outside the loop we will return the ans variable that will contain the numerical value of given roman string

C++ Code :-
#include <bits/stdc++.h>
using namespace std;
int romanToInt(string s) {
//unordered map that will store the value of roman character
unordered_map <char,int> mp = { {'I',1}, {'V',5}, {'X',10}, {'L',50}, {'C',100}, {'D',500}, {'M',1000} };
int ans=mp[s.back()];
for(int i=s.size()-2;i>=0;i--){
if(mp[s[i]]<mp[s[i+1]])
ans-=mp[s[i]];
else
ans+=mp[s[i]];
}
return ans;
}
int main()
{
//string str that will be passed to the function romanToInt too convert it into integer
string str="XI";
cout<<romanToInt(str);
return 0;
}
Output:-
11
Login/Signup to comment