leetcode12. 整数转罗马数字

贪心算法,先通过map将罗马字符和数字一一对应,进行有序排列,然后从最大的数字开始,进行数字到罗马字符的转换

class Solution {
public:
    string intToRoman(int num) {
        map map = {{1,    "I"},
                                {4,    "IV"},
                                {5,    "V"},
                                {9,    "IX"},
                                {10,   "X"},
                                {40,   "XL"},
                                {50,   "L"},
                                {90,   "XC"},
                                {100,  "C"},
                                {400,  "CD"},
                                {500,  "D"},
                                {900,  "CM"},
                                {1000, "M"}};
        auto reverse_iter = map.rbegin();
        string res;
        while (reverse_iter != map.rend()) {
            if (num >= reverse_iter->first) {
                num -= reverse_iter->first;
                res += reverse_iter->second;
            } else {
                reverse_iter++;
            }
        }
        return res;
    }
};

你可能感兴趣的:(leetcode12. 整数转罗马数字)