12. 整数转罗马数字

  1. 题目链接

  2. 解题思路:整数转罗马数字,可以理解为一个一个「数」,有一个转换表,从高位依次往低位「数」,直接看代码更清晰

  3. 代码

    class Solution {
    public:
        string intToRoman(int num) {
            // 转换表
            vector<pair<int, string>> table {
                {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"}
            };   
            int n = table.size();
            string ans = "";
            for (int i = n - 1; i >= 0; --i) {    
                while (num >= table[i].first) {   // 如果能转换高位的  一直转换
                    ans = ans + table[i].second;
                    num -= table[i].first;
                }
            }
            return ans;
        }
    };
    
posted @ 2024-12-18 09:21  ouyangxx  阅读(17)  评论(0)    收藏  举报