C++ Easy to Understand


  • 0
      class Solution {
      public:
      string intToRoman(int num) {
        string res;                      // output string
        vector<pair<string,int> > rel;   // relation between integers and roman numerals
        rel.push_back(make_pair("I",1));
        rel.push_back(make_pair("IV",4));
        rel.push_back(make_pair("V",5));
        rel.push_back(make_pair("IX",9));
        rel.push_back(make_pair("X",10));
        rel.push_back(make_pair("XL",40));
        rel.push_back(make_pair("L",50));
        rel.push_back(make_pair("XC",90));
        rel.push_back(make_pair("C",100));
        rel.push_back(make_pair("CD",400));
        rel.push_back(make_pair("D",500));
        rel.push_back(make_pair("CM",900));
        rel.push_back(make_pair("M",1000));
        while(num>0)
        {
            int i;
            for(i=rel.size()-1;i>=0;i--)
            {
                if(rel[i].second<=num) break; // find the first i backwards
            }
            res += rel[i].first;
            num = num - rel[i].second;
        }
        return res;
    }};

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.