Integer to Roman - CPP Solution

1. Introduction

This blog post covers the implementation of a function to convert an integer to its Roman numeral representation in C++. Roman numerals are a numeral system originating in ancient Rome, composed of combinations of letters from the Latin alphabet (I, V, X, L, C, D, and M).

Problem

The challenge is to write a function in C++ that converts an integer to a Roman numeral. Roman numerals are represented by seven different symbols: I (1), V (5), X (10), L (50), C (100), D (500), and M (1000).

2. Solution Steps

1. Store the Roman numeral representations for the significant digits.

2. Starting from the highest significant digit, find the numeral representation for each digit.

3. Concatenate these representations to form the final Roman numeral.

4. Handle each digit by comparing it with predefined values in descending order.

3. Code Program

#include <iostream>
#include <vector>
using namespace std;

// Function to convert an integer to a Roman numeral
string intToRoman(int num) {
    vector<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 roman;
    // Iterate over each symbol, starting from the largest
    for (const auto &valueSymbol : valueSymbols) {
        while (num >= valueSymbol.first) {
            num -= valueSymbol.first; // Subtract the value from the number
            roman += valueSymbol.second; // Append the Roman numeral symbol
        }
    }
    return roman;
}

int main() {
    int number = 58;
    cout << "Roman numeral of " << number << ": " << intToRoman(number) << endl;
    return 0;
}

Output:

Roman numeral of 58: LVIII

Explanation:

1. The input integer 58 is converted to a Roman numeral.

2. The function iterates over the predefined Roman numeral symbols from the largest to the smallest.

3. For each symbol, it checks how many times the symbol can fit into the remaining number.

4. The symbol is appended to the result for each fit, and the value of the symbol is subtracted from the number.

5. This process continues until the number is reduced to zero.

6. The final Roman numeral representation "LVIII" is obtained, which is the correct representation for 58.


Comments