Thursday, October 19, 2017

12. Integer to Roman

https://leetcode.com/problems/integer-to-roman/description/
    string intToRoman(int num) {
        map<int, string, greater<int>> I2R = {
            {1000, "M"}, {500, "D"}, {100, "C"}, {50, "L"}, {10, "X"}, {5, "V"}, {1, "I"},
            {900, "CM"}, {400, "CD"}, {90, "XC"}, {40, "XL"}, {9, "IX"}, {4, "IV"}
        };
        string res;
        for(auto const& r : I2R) {
            int c = num/r.first;
            if(c==1) { res += r.second; num -= r.first;}
            else if(c>1) { res += string(c, r.second[0]); num -= c*r.first;}
        }
        return res;
    }
or,
    string intToRoman(int num) {
        string res;
        vector<string> M = {"", "M", "MM", "MMM"};
        vector<string> C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        vector<string> X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        vector<string> I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
    }

No comments:

Post a Comment