My C++ 28ms solution


  • 0
    M

    My C++ 28ms solution

    class Solution {
    public:
        string intToRoman(int num) {
            if(num<1 || num>3999) return "0";
            char roman[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
                            //1    5    10   50   100  500  1000
            string result;
            int digit = 6, k;
            for(int i=1000; i!=0; i/=10){
                k = num / i;
                if(k == 0){
                    digit -= 2;
                    continue;
                }
                if(k==4){
                    result = result + roman[digit] + roman[digit+1];
                    digit -= 2;
                    num = num % i;
                    continue;
                }
                if(k==9){
                    result = result + roman[digit] + roman[digit+2];
                    digit -= 2;
                    num = num % i;
                    continue;
                }
                if(k>=5){
                    result = result + roman[digit+1];
                    k -= 5;    
                }
                while(k){
                    result = result + roman[digit];
                    k--;
                }
                digit -= 2;
                num = num % i;
            }
            return result; 
        }
    };
    

Log in to reply
 

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