Leetcode – Integer to Roman

Name: Integer to Roman
Difficulty: Medium
Description: Convert an integer to Roman Numerals

Example:

Input: num = 3
Output: "III

Input: num = 58
Output: "LVIII"

Input: num = 1994
Output: "MCMXCIV"

Just used a simple approach for this one, it’s self-explanatory.

static void repeat(string& s, int count, char c){
    while(count-- > 0) s.push_back(c);
}

string intToRoman(int num) {
    string res = "";

    if (num >= 1000) {
        repeat(res, num / 1000, 'M');
        num %= 1000;
    }

    if (num >= 900) {
        res += "CM";
        num -= 900;
    }

    if (num >= 500) {
        repeat(res, num / 500, 'D');
        num %= 500;
    }

    if (num >= 400) {
        res += "CD";
        num -= 400;
    }

    if (num >= 100) {
        repeat(res, num / 100, 'C');
        num %= 100;
    }

    if (num >= 90) {
        res += "XC";
        num -= 90;
    }

    if (num >= 50) {
        repeat(res, num / 50, 'L');
        num %= 50;
    }

    if (num >= 40) {
        res += "XL";
        num %= 40;
    }

    if (num >= 10) {
        repeat(res, num / 10, 'X');
        num %= 10;
    }

    if (num == 9) return res + "IX";
    
    if (num >= 5) {
        repeat(res, num / 5, 'V');
        num %= 5;
    }

    if (num == 4) return res + "IV";

    if (num > 0) {
        repeat(res, num, 'I');
    }

    return res;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s