Roman Numeral Converter in C++
This program converts numbers to Roman numerals and vice versa. It is implemented in C++ and includes detailed explanations and documentation for clarity.
Program Structure
The program consists of the following components:
- romanToInt: Converts a Roman numeral string to an integer.
- intToRoman: Converts an integer to a Roman numeral string.
- main: Entry point of the program where conversion functions are demonstrated.
C++ Code
// RomanNumeralConverter.cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
/**
* Function to convert Roman numeral to integer.
* @param s: Roman numeral string.
* @return Integer representation of the Roman numeral.
*/
int romanToInt(const string &s) {
unordered_map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
int total = 0;
int prevValue = 0;
for (const char &c : s) {
int currValue = roman[c];
if (currValue > prevValue) {
total += currValue - 2 * prevValue;
} else {
total += currValue;
}
prevValue = currValue;
}
return total;
}
/**
* Function to convert integer to Roman numeral.
* @param num: Integer value.
* @return Roman numeral representation of the integer.
*/
string intToRoman(int num) {
pair<int, string> valueSymbols[] = {
{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},
{10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}
};
string result;
for (const auto &pair : valueSymbols) {
while (num >= pair.first) {
result += pair.second;
num -= pair.first;
}
}
return result;
}
int main() {
// Examples of conversion
string romanNumeral = "MCMXCIV";
int number = 1994;
cout << "Roman numeral " << romanNumeral << " is " << romanToInt(romanNumeral) << " in integer." << endl;
cout << "Integer " << number << " is " << intToRoman(number) << " in Roman numeral." << endl;
return 0;
}
Explanation
The program contains two main functions: romanToInt and intToRoman.
romanToInt Function
- Uses an unordered map to store the Roman numeral characters and their corresponding integer values.
- Iterates through the input string and computes the integer value by checking if the current Roman numeral is greater than the previous one.
- If the current numeral is greater, it subtracts twice the previous value (since it was added once before) and adds the current value.
- Otherwise, it adds the current value directly to the total.
intToRoman Function
- Uses an array of pairs to store integer values and their corresponding Roman numeral strings, sorted from largest to smallest.
- Iterates through the array and appends the Roman numeral string to the result while subtracting the integer value from the number until the number becomes zero.
main Function
- Demonstrates the conversion by converting a Roman numeral string to an integer and an integer to a Roman numeral string.
- Outputs the results to the console.