My C++ solution beat 95%


  • 4
    string intToRoman(int num) {
            int i=0;
            string a = "IVXLCDM", res = "";
            while(num)
            {
                int temp = num%10;
                if(temp<=3) res = string(temp,a[i])+res;
                else if(temp==4) res = string(1,a[i])+string(1,a[i+1])+res;
                else if(temp==5) res = string(1,a[i+1])+res;
                else if(temp<=8) res = string(1,a[i+1])+string(temp-5,a[i])+res;
                else if(temp==9) res = string(1,a[i])+string(1,a[i+2])+res;
                num = num/10;
                i += 2;
            }
            return res;
        }
    

Log in to reply
 

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