Home >>Cpp Programs >C++ Program to Convert Roman Number to Integer Number

C++ Program to Convert Roman Number to Integer Number

C++ Program to Convert Roman Number to Integer Number

In this example, we will see a C++ program through which we can convert a roman number into an integer number.

Algorithm:
• Step 1: Declare all the Roman characters and its integer value
in an Array ( ramp[] ).
• Step 2: If (Length of roman) =<1
Return corresponding Array index value.
• Step 3:else Repeat step 4 and step 5, While((i<roman.size())
• Step 4:if(rmap[roman[i]]<rmap[roman[i+1]])
number+=rmap[roman[i+1]]-rmap[roman[i]]
i+=2;
• Step 5:else
number+=rmap[roman[i]]
i++
• Step 6:return the number
Program:
``````
#include <bits/stdc++.h>
using namespace std;
int roman_to_int(string roman){
map<char,int> rmap;
rmap['I'] =   1;
rmap['V'] =   5;
rmap['X'] =  10;
rmap['L'] =  50;
rmap['C'] = 100;
rmap['D'] = 500;
rmap['M'] =1000;
int number=0,i=0;
//If input is only one character
if(roman.length()<=1){
return rmap[roman.at(0)];
}
else{
while(i<roman.size()){
if(rmap[roman[i]]<rmap[roman[i+1]]){
number+=rmap[roman[i+1]]-rmap[roman[i]];
i+=2;
}
else{
number+=rmap[roman[i]];
i++;
}
}
return number;
}
}
int main(){
string roman;
cout<<"Enter the roman number (in capital only): ";
getline(cin,roman);
int number;
number=roman_to_int(roman);
cout<<"The interger form is: "<<number;
return 0;
}
```
```
Output:
Enter the roman number (in capital only): XXX
The interger form is: 30