My simple cpp solution


  • 5
    C
    class Solution {
    public:
        string intToRoman(int num) 
        {
            string res;
            string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
            int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
            
            for(int i=0; num != 0; i++)
            {
                while(num >= val[i])
                {
                    num -= val[i];
                    res += sym[i];
                }
            }
            
            return res;
        }
    };

  • 0
    S

    class Solution {
    public:
    string intToRoman(int num) {

        // Making the first 3 arrays char* rather than string reduces runtime from 36 to 32 ms
        static char* ones[10] =     { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
        static char* tens[10] =     { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
        static char* hundreds[10] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
        static string thousands[4] = { "", "M", "MM", "MMM" };
        
        int th = num/1000;
        num -= th*1000;
        int h = num/100;
        num -= h*100;
        int t = num/10;
        int o = num - t*10;
        
        return thousands[th]+hundreds[h]+tens[t]+ones[o];
    }
    

    };


Log in to reply
 

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