Question: Convert an roman integer in its decimal equivalent.

Code:

//Assumption: only valid string containing following Roman numerlas are entered.
// MDCLXVI

#include<iostream>
#include<string.h>
using namespace std;

main()
{
char in[10], outn[100];
long int out=0;
cout << "Enter Roman String (Characters allowed are M,D,C,L,X,V,I) : "<<endl;
cin >> in;

int len = strlen(in);
int i = 0;
int lastval = 1000;

while(in[i] != '\0')
{
switch (in[i])
{
case 'M':
case 'm':
out = out + 1000;
if (lastval < 1000)
out = out - 2*lastval;
lastval = 1000;
break;

case 'D':
case 'd':
out = out + 500;
if (lastval < 500)
out = out - 2*lastval;
lastval = 500;
break;

case 'C':
case 'c':
out = out + 100;
if (lastval < 100)
out = out - 2*lastval;
lastval = 100;
break;

case 'L':
case 'l':
out = out + 50;
if (lastval < 50)
out = out - 2*lastval;
lastval = 50;
break;

case 'X':
case 'x':
out = out + 10;
if (lastval < 10)
out = out - 2*lastval;
lastval = 10;
break;

case 'V':
case 'v':
out = out + 5;
if (lastval < 5)
out = out - 2*lastval;
lastval = 5;
break;

case 'I':
case 'i':
out = out + 1;
if (lastval < 1)
out = out - 2*lastval;
lastval = 1;
break;

default:
cout << "Invalid Input" <<endl;
break;
}
i++;
}

cout << "Decimal Equivalent = " << out <<endl;
}

Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.