C++ solution without enumeration, 36ms


  • 0
    A
    class Solution {
    public:
        string intToRoman(int num) {
        int romanLetterInt[] = {1000, 500, 100, 50, 10, 5, 1};
        char romanLetter[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
        
        string roman = "";
        for(int i = 0; i < 7 && num != 0; ) {
            int tmp = num / romanLetterInt[i];
            if(tmp == 0) {
                int indexTmp = num > 100 ? 2 : num > 10 ? 4 : 6;
                int resTmp = num / romanLetterInt[indexTmp];
                if(resTmp != 0 && romanLetterInt[i] == (resTmp + 1) * romanLetterInt[indexTmp]) {
                    roman = roman + romanLetter[indexTmp] + romanLetter[i];
                    num %= romanLetterInt[indexTmp];
                }
                i++;
            } else {
                while(tmp--)
                    roman += romanLetter[i];
                num %= romanLetterInt[i];
            }
        }
        return roman;
        }
    };

Log in to reply
 

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