Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

12. Integer to Roman 🌟🌟

Given a number in the range 1 to 3999, return the number in Roman numeral format.

Greedy solution

Code

class Solution {
public:
    string intToRoman(int num)
    {
        // Check for invalid inputs
        if (num < 1 || num > 3999) return "";

        vector<int> values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        vector<string> romans = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

        string res = "";
        int i = 0;
        while (num > 0) {
            if (num - values[i] >= 0) {
                res += romans[i];
                num -= values[i];
            } else {
                i++;
            }
        }
        return res;
    }
};

Fun solution

Code

class Solution {
public:
    string intToRoman(int num)
    {
        vector<string> ones = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
        vector<string> tens = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
        vector<string> hundreds = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
        vector<string> thousands = { "", "M", "MM", "MMM" };
        return thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
    }
};