My Fussy C++ Solution


  • 0
    S
    //Solution 1 -- 85 ms 14.59%
    class Solution {
    public:
        string intToRoman(int num) {
            int reminder = 0;
            int count = 0;
            string result;
            while(num){
                reminder = num % 10;
                count++;
                if(reminder == 9) 
                    result = intTostring(1, count) + intTostring(10, count) + result;
                else if(reminder >= 5){
                        while(reminder > 5){
    	                    result = intTostring(1, count) + result;
    	                    reminder--;
    	                }
    	                result = intTostring(5, count) + result;
                }
                else if(reminder < 5 && reminder > 0){
    	               if(reminder == 4){
    	                    result = intTostring(1, count) + intTostring(5, count) + result;
    	               }
    	               else{
    	                    while(reminder){
    	                        result = intTostring(1, count) + result;
    	                        reminder--;
    	                    }
    	               }
    	        }
                num /= 10;
            }
            return result;
        }
        
        string intTostring(int reminder, int count) {
            string result = "";
            switch(count){
                case 1:
                    if(reminder == 1) result = "I";
                    if(reminder == 2) result = "II";
                    if(reminder == 3) result = "III";
                    if(reminder == 4) result = "IV";
                    if(reminder == 5) result = "V";
                    if(reminder == 10) result = "X";
                    break;
                case 2:
                    if(reminder == 1) result = "X";
                    if(reminder == 5) result = "L";
                    if(reminder == 10) result = "C";
                    break;
                case 3:
                    if(reminder == 1) result = "C";
                    if(reminder == 5) result = "D";
                    if(reminder == 10) result = "M";
                    break;
                case 4:
                    if(reminder == 1) result = "M";
                    break;
            }
            return result;
        }
    };

Log in to reply
 

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