Sharing my solution with 28ms


  • 0
    T
    class Solution {
    public:
        string intToRoman(int num) {
            string res;
            char list[7] = {'I','V','X','L','C','D','M'};
    
            int last_digit = 0;
            int count = 0;
            while(num != 0) {
                last_digit = num % 10;
                if (last_digit == 4) {
                    res.insert(res.begin(), list[2*count+1]);
                    res.insert(res.begin(), list[2*count]);
                }
                else if (last_digit == 9) {
                    res.insert(res.begin(), list[2*count+2]);
                    res.insert(res.begin(), list[2*count]);
                }
                else {
                    if (last_digit < 4) {
                        while(last_digit != 0) {
                            res.insert(res.begin(), list[2*count]);
                            last_digit--;
                        }
                    }
                    else {
                        last_digit -= 5;
                        while(last_digit != 0) {
                            res.insert(res.begin(), list[2*count]);
                            last_digit--;
                        }
                        res.insert(res.begin(), list[2*count+1]);
                    }
                }
                num = num / 10;
                count++;
            }
            return res;
        }
    };

Log in to reply
 

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