c++ solution


  • 0
    B
    class Solution {
    public:
        
        string constructRoman(char start, char mid, char end, int num){
            if(num == 0){
                return "";
            }
            if(num >=1 and num <= 3){
                return string(num,start);
            } else if( num == 4){
                return string(1,start).append(1,mid);
            } else if( num == 5){
                return string(1,mid);
            } else if(num >=6 && num <=8){
                return mid+string(num-5, start);
            } else if(num == 9) {
                return string(1,start).append(1,end);
            }
        }
        string intToRoman(int num) {
            stack<string> res;
            // Stack to store the intermidiate result
            // process each digit at a time, from least significant to most
            if(num>0){
                res.push(constructRoman('I', 'V', 'X', num%10));
            }
            if(num >=10){
                res.push(constructRoman('X', 'L', 'C', (num/10) %10));
            }
            if(num >= 100){
                res.push(constructRoman('C', 'D', 'M', (num/100) %10));
            }
            if(num >= 1000){
                res.push(constructRoman('M', 'V', 'X', (num/1000) %10));
            }
            string result;
            while(!res.empty()){
                result.append(res.top());
                res.pop();
            }
            return result;
        }
    };
    

Log in to reply
 

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