Drill

ProblemsC++ › warmup

Write a number in Roman numerals

mediumwarmupMathStringsGreedyC++

A film credit or a chapter heading wants MCMXCIV rather than 1994.

toRoman(amount: int) → string

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::string toRoman(int amount) {
    
}

Worked examples

CallResult
toRoman(1)std::string("I")
toRoman(4)std::string("IV")
toRoman(14)std::string("XIV")
toRoman(1994)std::string("MCMXCIV")

Hint

Keep the values and their symbols in one descending table, including the subtractive pairs. Then it is one greedy pass.

Reference solution in C++
std::string toRoman(int amount) {
    if (amount < 1 || amount > 3999) return "";
    int vals[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    const char* syms[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    int n = amount;
    string result;
    for (int i = 0; i < 13; i++) {
        while (n >= vals[i]) { result += syms[i]; n -= vals[i]; }
    }
    return result;
}

The same problem in another language

More warmup problems in C++