programa en C ++ para convertir número romano para Número Entero

En este artículo, vamos a aprender, cómo podemos convertir un número romano en forma de número entero usando C ++ programa ?

Dado un número en formato romana y tenemos que convertirlo en formato de enteros / decimales.

Ejemplo:

    Input: XIV
Output: 14
Input: XI
Output: 11

Algoritmo:

roman_to_int (cadena romano)

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

Programa:

#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;
}

de salida

Enter the roman number (in capital only): XIV
The interger form is: 14

Explicación:

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.


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *