My C++ solution 36ms


  • 0
    D
    string intToRoman(int num) {
        int base[] = {1000,900,990,999,500,400,490,499,100,90,99,50,40,49,10,9,5,4,1};
        string T[] = {"M","CM","XM","IM","D","CD","XD","ID","C","XC","IC","L","XL","IL","X","IX","V","IV","I"};
        
        int i = 0;
        string res;
        while (num) {
            if (num-base[i] >= 0) {
                num -= base[i];
                res += T[i];
            }
            else {
                i++;
            }
        }
        return res;
    }

  • 0
    S

    The base value (1, 10, 100, 1000, etc) should only be mixed with it's 5 and 10 multipliers.
    i.e. you should write 999 as "CMXCIX" instead of "IM". I guess in your code they will never actually get hit because subtracting 900 will invalidate the options for "XM" and "IM". You could remove the reference to them and make fewer iterations in your loop.


Log in to reply
 

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