My C++ solution without listing so many occurrences.


  • 1
    M

    My C++ solution without listing so many occurrences.

    string intToRoman(int num) {
        int roman[7] = {1000,500,100,50,10,5,1};
        string r = "MDCLXVI";
        string output = "";
    
        int i = 0 ;
        while(num>0)
        {
    
            if(num < roman[i]) 
            {
                int c = (i&1)? 1:2;
    
                if(num + roman[i+c] >= roman[i])
                {
                    output = output + r[i+c] + r[i];
                    num = num + roman[i+c] - roman[i];
                }
    
                i++;
            }
            else
            {
                output += r[i];
                num = num - roman[i];
            }
        }
        return output;
    }

Log in to reply
 

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