My C++ solution, 27ms.


  • -1
    B
    class Solution {
    public:
        string intToRoman(int num) {
            int k=num/1000;
            num=num%1000;
            int h=num/100;
            num%=100;
            int t=num/10;
            num%=10;
            string ans="";
            switch(k)
            {
                case 3:ans+="MMM";break;
                case 2:ans+="MM";break;
                case 1:ans+="M";break;
                default:break;
            }
            switch(h)
            {
                case 9:ans+="CM";break;
                case 8:ans+="DCCC";break;
                case 7:ans+="DCC";break;
                case 6:ans+="DC";break;
                case 5:ans+="D";break;
                case 4:ans+="CD";break;
                case 3:ans+="CCC";break;
                case 2:ans+="CC";break;
                case 1:ans+="C";break;
                default:break;
            }
            switch(t)
            {
                case 9:ans+="XC";break;
                case 8:ans+="LXXX";break;
                case 7:ans+="LXX";break;
                case 6:ans+="LX";break;
                case 5:ans+="L";break;
                case 4:ans+="XL";break;
                case 3:ans+="XXX";break;
                case 2:ans+="XX";break;
                case 1:ans+="X";break;
                default:break;
            }
            switch(num)
            {
                case 9:ans+="IX";break;
                case 8:ans+="VIII";break;
                case 7:ans+="VII";break;
                case 6:ans+="VI";break;
                case 5:ans+="V";break;
                case 4:ans+="IV";break;
                case 3:ans+="III";break;
                case 2:ans+="II";break;
                case 1:ans+="I";break;
                default:break;
            }
            return ans;
        }
    };

Log in to reply
 

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