Converting Roman Numerals to Decimal lying between 1 to 3999 in C++



In this tutorial, we will be discussing a program to converting roman numerals to decimal lying between 1 to 3999.

For this we will be provided with a random roman numeral. Our task is to convert the given roman numeral into its decimal equivalent.

Example

 Live Demo

#include<bits/stdc++.h> using namespace std; //calculating the decimal value int value(char r){    if (r == 'I')    return 1;    if (r == 'V')    return 5;    if (r == 'X')    return 10;    if (r == 'L')    return 50;    if (r == 'C')    return 100;    if (r == 'D')    return 500;    if (r == 'M')    return 1000;    return -1; } //calculating decimal equivalent of given numeral int convert_decimal(string &str){    int res = 0;    for (int i=0; i<str.length(); i++){       //getting value of digit       int s1 = value(str[i]);       if (i+1 < str.length()){          int s2 = value(str[i+1]);          if (s1 >= s2){             res = res + s1;          }          else{             res = res + s2 - s1;             i++;          }       }       else{          res = res + s1;       }    }    return res; } int main(){    string str ="MCMIV";    cout << "Integer form:"    << convert_decimal(str) << endl;    return 0; }

Output

Integer form:1904
Updated on: 2020-01-29T07:40:25+05:30

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements