c++ Direct easy to understand Brute Force Solution


  • 0

    If you observe there is a specific symbol to represent a particular digit in units place, tens place, hundred's place and thousands place.

    In the below code I am iterating through the digits from unit's place to ten's place and so on.

    When i reach the highest digit place i start printing that particular symbol and return .......till i reach unit's place.

    class Solution {
    public:
        string s = "";
        string intToRoman(int num) {
            store(num,0);
            return s;
        }
        void store(int num,int i){
            if(num == 0)
                return;
            store(num/10,i+1);
            int x = num % 10;
            printrom(x,i);
        }
        
        void printrom(int x, int i){
            string t = "",f = "",n = "";
            if(i == 0){
                t = "X";
                f = "V";
                n = "I";
            }
            else if(i == 1){
                t = "C";
                f = "L";
                n = "X";
            }else if(i == 2){
                t = "M";
                f = "D";
                n = "C";
            }else if(i == 3){
                n = "M";
            }
            switch(x){
                case 1:
                    s += n;
                    break;
                case 2:
                    s += n+n;
                    break;
                case 3:
                    s += n+n+n;
                    break;
                case 4:
                    s += n+f;
                    break;
                case 5:
                    s += f;
                    break;
                case 6:
                    s += f+n;
                    break;
                case 7:
                    s += f+n+n;
                    break;
                case 8:
                    s += f+n+n+n;
                    break;
                case 9:
                    s += n+t;
                    break;
            }
        }
    };
    

Log in to reply
 

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