KatInterview

12. Integer to Roman

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires converting a given integer into its Roman numeral equivalent. The input integer is guaranteed to be within the range of 1 to 3999. The core of the problem lies in correctly applying the rules of Roman numeral formation, which include standard additive notation (e.g., VI for 6) and special subtractive notation (e.g., IV for 4, IX for 9).

Solution

Integer to Roman in Python

class Solution:
    def intToRoman(self, num: int) -> str:
        # Create a mapping of values to Roman numeral symbols, including subtractive cases.
        # The list must be sorted in descending order for the greedy approach to work.
        value_symbols = [
            (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")
        ]
        
        result_parts = []
        
        # Iterate through the value-symbol pairs from largest to smallest.
        for value, symbol in value_symbols:
            # If num is 0, we can stop early.
            if num == 0:
                break
            
            # Greedily subtract the largest possible value from num
            # and append the corresponding symbol to the result.
            count, num = divmod(num, value)
            if count > 0:
                result_parts.append(symbol * count)
        
        return "".join(result_parts)

Integer to Roman in Java

class Solution {
    public String intToRoman(int num) {
        // Create a mapping of values to Roman numeral symbols, including subtractive cases.
        // The list must be sorted in descending order for the greedy approach to work.
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        
        StringBuilder result = new StringBuilder();
        
        // Iterate through the values from largest to smallest.
        for (int i = 0; i < values.length && num > 0; i++) {
            // Greedily subtract the largest possible value from num
            // and append the corresponding symbol to the result.
            while (num >= values[i]) {
                num -= values[i];
                result.append(symbols[i]);
            }
        }
        
        return result.toString();
    }
}

Integer to Roman in C++

class Solution {
public:
    string intToRoman(int num) {
        // Create a mapping of values to Roman numeral symbols, including subtractive cases.
        // The list must be sorted in descending order for the greedy approach to work.
        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 result = "";
        
        // Iterate through the value-symbol pairs from largest to smallest.
        for (const auto& pair : valueSymbols) {
            int value = pair.first;
            string symbol = pair.second;
            
            // Greedily subtract the largest possible value from num
            // and append the corresponding symbol to the result.
            while (num >= value) {
                result += symbol;
                num -= value;
            }
            
            // Optimization: if num becomes 0, we can stop early.
            if (num == 0) {
                break;
            }
        }
        
        return result;
    }
};

Integer to Roman in TypeScript

function intToRoman(num: number): string {
    // Create a mapping of values to Roman numeral symbols, including subtractive cases.
    // The list must be sorted in descending order for the greedy approach to work.
    const valueSymbols: {value: number, symbol: string}[] = [
        {value: 1000, symbol: "M"}, {value: 900, symbol: "CM"}, {value: 500, symbol: "D"}, {value: 400, symbol: "CD"},
        {value: 100, symbol: "C"}, {value: 90, symbol: "XC"}, {value: 50, symbol: "L"}, {value: 40, symbol: "XL"},
        {value: 10, symbol: "X"}, {value: 9, symbol: "IX"}, {value: 5, symbol: "V"}, {value: 4, symbol: "IV"}, {value: 1, symbol: "I"}
    ];

    let result = '';

    // Iterate through the value-symbol pairs from largest to smallest.
    for (const { value, symbol } of valueSymbols) {
        // Greedily subtract the largest possible value from num
        // and append the corresponding symbol to the result.
        while (num >= value) {
            result += symbol;
            num -= value;
        }

        // Optimization: if num becomes 0, we can stop early.
        if (num === 0) {
            break;
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.