leetcode 12 Integer to Roman numerals greedy

Forehead, attached two greedy?

This is a local optimization problem: use large "number indicates Rome" will not use small.

First construct the basis of all Roman numbers, then descending compare

Because the comparison is only 1000,900, ... limited and some trouble, constructed table map <int, string>

Then, Map default installation values sorted in ascending order of the key ..

I think big to small, with 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.gives ()) 
        {
            if(num >= iter->first)
            {
                ret += iter->second;
                num-= iter->first;
            }
            else
                iter++;
        }
        return ret;
    }
};

 

Guess you like

Origin www.cnblogs.com/lqerio/p/11750057.html