My C++ 28 ms solutions (no loop and no nested loop)


  • 1
    X

    I first write this no loop version:

    class Solution {
    public:
        string intToRoman(int num) {
            string s;
            if (num >= 2000) {
                s += "MM";
                num -= 2000;
            }
            if (num >= 1000) {
                s += "M";
                num -= 1000;
            }
            if (num >= 900) {
                s += "CM";
                num -= 900;
            }
            if (num >= 500) {
                s += "D";
                num -= 500;
            }
            if (num >= 400) {
                s += "CD";
                num -= 400;
            }
            if (num >= 200) {
                s += "CC";
                num -= 200;
            }
            if (num >= 100) {
                s += "C";
                num -= 100;
            }
            if (num >= 90) {
                s += "XC";
                num -= 90;
            }
            if (num >= 50) {
                s += "L";
                num -= 50;
            }
            if (num >= 40) {
                s += "XL";
                num -= 40;
            }
            if (num >= 20) {
                s += "XX";
                num -= 20;
            }
            if (num >= 10) {
                s += "X";
                num -= 10;
            }
            if (num >= 9) {
                s += "IX";
                num -= 10;
            }
            if (num >= 5) {
                s += "V";
                num -= 5;
            }
            if (num == 4) {
                s += "IV";
                return s;
            }
            if (num >= 2) {
                s += "II";
                s -= 2;
            }
            if (num == 1)
                s += "I";
            return s;
        }
    };
    

    Then I clean it up with loop:

    class Solution {
    public:
        string intToRoman(int num) {
            static const int ns[] =   {2000,1000, 900,500, 400, 200,100,  90, 50,  40,  20, 10,  9,   5,   4,   2,  1};
            static const char* ss[] = {"MM", "M","CM","D","CD","CC","C","XC","L","XL","XX","X","IX","V","IV","II","I"};
            string s;
            s.reverse(64);
            for (auto i = 0; num > 0; ++i) {
                if (num >= ns[i]) {
                    num -= ns[i];
                    s += ss[i];
                }
            }
            return s;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.