12 Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

class Solution {
public:
    string intToRoman(int num) {
        /*
        I   V   X   L   C   D   M
        1   5   10  50  100 500 1000
        */
        string res = "";
        for ( int i = 1; i <= num/1000; i++ ) res += "M";
        num = num%1000;
        if ( num >= 900 ) res += "CM";
        if ( num >= 500 and num < 900 ) {
            res += "D";
            for ( int i = 1; i <= (num-500)/100; i++ ) res += "C";
        }
        if ( num >= 400 and num < 500 ) res += "CD";
        if ( num < 400 ) {
            for ( int i = 1; i <= num/100; i++ ) res += "C";
        }
        num = num%100;
        if ( num >= 90 ) res += "XC";
        if ( num >= 50 and num < 90 ) {
            res += "L";
            for ( int i = 1; i <= (num-50)/10; i++ ) res += "X";
        }
        if ( num >= 40 and num < 50 ) res += "XL";
        if ( num < 40 ) {
            for ( int i = 1; i <= num/10; i++ ) res += "X";
        }
        num = num%10;
        if ( num >= 9 ) res += "IX";
        if ( num >= 5 and num < 9 ) {
            res += "V";
            for ( int i = 1; i <= num-5; i++ ) res += "I";
        }
        if ( num >= 4 and num < 5 ) res += "IV";
        if ( num < 4 ) {
            for ( int i = 1; i <= num; i++ ) res += "I";
        }
        return res;
    }
};

results matching ""

    No results matching ""