Q:

C++ program to Convert Roman Number to Integer Number

0

Given a number in Roman format and we have to convert it into integer/decimal format.

Example:

    Input: XIV
    Output: 14

    Input: XI
    Output: 11

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

roman_to_int(string roman)

Step 1: Declare all Roman characters and its integer value 
        in a Array ( rmap[] ) where Index=’Roman_character’
Step 2: If (Length of roman) =<1
            Return corresponding Array index value.
Step 3: else
Step 4: Repeat step 5 and step 6, While((i<roman.size()) 
Step 5: if(rmap[roman[i]]<rmap[roman[i+1]])
            number+=rmap[roman[i+1]]-rmap[roman[i]]		
            //number is storing the integer number 
            //after conversion; number=0
            i+=2;
Step 6: else
        number+=rmap[roman[i]]
        i++
Step 7:
return 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): XIV
The interger form is: 14

Explanation:

 
Sample Input : XIV
=>  String lenght is >1, so it is "else" part of roman_to_int() 
will execute here.
Step1:  
i=0, so, 0<3 (size of string), while loop will execute.
Now, rmap[roman[0]]=rmap[X] that is equal to 10, and 
rmap[roman[1]]=1,
So, 10<1 that is false, so "else" part inside the while loop 
will execute and 
number+=rmap[roman[i]];
=> number=0+10
=>number=10 and i=0+1 that is i=1
Step2:
i=1, so, 1<3, again while loop will execute.
Now, rmap[roman[1]]=rmap[I] that is eaual to 1 and 
rmap[roman[2]]=5,
So, 1<5, that is true... So, if part inside the while loop will 
execute and
number+=rmap[roman[i+1]]-rmap[roman[i]];
=>number+=rmap[V]-rmap[I]
=>number+=5-1
=>number+=4
=>number=10+4
=>number=14
And, i=i+2 that is i=3
Step3:
i=3, so, 3<3 that is false.

So, return value will be 14.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now