码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 12 整数转罗马数字 贪心

时间:2019-10-28 09:11:50      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:安装   public   基础   tco   first   罗马数字   整数   pre   iterator   

额,连着两个贪心?

这是局部最优问题:能用大“罗马数表示”就不会用小的。

构造出所有基础罗马数,然后从大到小比较

因为比较的只有1000,900,...有限并有些麻烦,构造table  map<int,string>

然后,map默认安装按照key的值升序排序..

想从大到小,用reverse_iterator

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

 

leetcode 12 整数转罗马数字 贪心

标签:安装   public   基础   tco   first   罗马数字   整数   pre   iterator   

原文地址:https://www.cnblogs.com/lqerio/p/11750057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!