Reduced memory C++ version


  • 0
    C
    class Solution {
    public:
        void num_to_roman( char one, char five, char ten, int num, string &roman )
        {
            switch (num)
            {
                case 1: roman.append( 1, one );  break;
                case 2: roman.append( 2, one );  break;
                case 3: roman.append( 3, one );  break;
                case 4: roman.append( 1, one );  roman.append( 1, five ); break;
                case 5: roman.append( 1, five ); break;
                case 6: roman.append( 1, five ); roman.append( 1, one ); break;
                case 7: roman.append( 1, five ); roman.append( 2, one ); break;
                case 8: roman.append( 1, five ); roman.append( 3, one ); break;
                case 9: roman.append( 1, one );  roman.append( 1, ten ); break;
                default: break;
            }
        }
    
        string intToRoman(int num) {
            // I = 1, II, III, IV, V, VI, VII, VIII, IX
            // X = 10, XX, XXX, XL, LX, LXX, LXXX, XC
            // C = 100, CC, CCC, CD, D, DC, DCC, DCCC, CM
            // M = 1000, MM, MMM
            const char   roman_ones[]  = { 'M', 'C', 'X', 'I' };
            const char   roman_fives[] = { '\0',  'D', 'L', 'V' };
            const char   roman_tens[]  = { '\0',  'M', 'C', 'X' };
            string roman_str;   
            int    divisor = 1000;
            int    i = 0;
            while ( divisor > 0 )
            {
                num_to_roman( roman_ones[i], roman_fives[i], roman_tens[i], num/divisor, roman_str );   
                num = num % divisor;
                divisor = divisor/10;
                i++;
            }
            
            return roman_str;
        }
    };
    

Log in to reply
 

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