The Program in C++ Program to Convert Given Roman Numeral to Integer is given below:
#include <iostream>
#include <map>
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;
}
int romanToInt(std::string &str) {
int res = 0;
for (int i = 0; i < str.length(); i++) {
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;
i++;
}
}
return res;
}
int main() {
std::string romanNumeral;
std::cout << "Hello Codeauri Family,enter a Roman numeral here to find out the equivalent integer: ";
std::cin >> romanNumeral;
int integer = romanToInt(romanNumeral);
std::cout << "Okay,the equivalent integer is: " << integer << std::endl;
return 0;
}
Output:
Hello Codeauri Family,enter a Roman numeral here to find out the equivalent integer: CCC
Okay,the equivalent integer is: 300
Pro-Tips💡
In this program, the function value
maps a Roman numeral character to its corresponding integer value.
The function romanToInt
takes a std::string
argument, which represents the Roman numeral, and converts it to an integer.
Finally, the main function prompts the user to enter a Roman numeral and displays the equivalent integer.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.