lqerio

额,连着两个贪心?

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

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

因为比较的只有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;
    }
};

 

分类:

技术点:

相关文章:

  • 2021-12-17
  • 2022-01-16
  • 2022-01-19
  • 2022-02-01
  • 2021-07-23
  • 2022-12-23
  • 2022-01-17
  • 2021-12-23
猜你喜欢
  • 2021-08-07
  • 2021-12-25
  • 2022-02-11
  • 2022-01-14
  • 2021-12-24
  • 2022-01-18
  • 2022-02-11
相关资源
相似解决方案