How to convert an integer to Roman numerals in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>

std::string intToRoman(int num) {
    // Define values and their corresponding Roman numerals
    std::vector<int> values   = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    std::vector<std::string> symbols = {
        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
    };

    std::string roman;

    // Loop through values and subtract while possible
    for (size_t i = 0; i < values.size(); ++i) {
        while (num >= values[i]) {
            num -= values[i];
            roman += symbols[i]; // append symbol
        }
    }

    return roman;
}

int main() {
    std::cout << intToRoman(1994) << std::endl;
    std::cout << intToRoman(196)  << std::endl; 
    std::cout << intToRoman(9)    << std::endl; 
}


/*
run:

MCMXCIV
CXCVI
IX

*/

 



answered Apr 23, 2025 by avibootz
edited Dec 1, 2025 by avibootz
...