首页 > 代码库 > 12. Integer to Roman

12. Integer to Roman

百度百课中相关介绍说明:

罗马数字含有:Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。

记数的方法:
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
  3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
  4. 在一个数的上面画一条横线,表示这个数增值 1,000 倍。

 

 

class Solution {
public:
    string intToRoman(int num) {
         map <int , string > RomanMap;
         RomanMap[1000] = "M";
         RomanMap[2000] = "MM";
         RomanMap[3000] = "MMM";
         RomanMap[100] = "C";
         RomanMap[200] = "CC";
         RomanMap[300] = "CCC";
         RomanMap[400] = "CD";
         RomanMap[500] = "D";
         RomanMap[600] = "DC";
         RomanMap[700] = "DCC";
         RomanMap[800] = "DCCC";
         RomanMap[900] = "CM";

         RomanMap[10] = "X";
         RomanMap[20] = "XX";
         RomanMap[30] = "XXX";
         RomanMap[40] = "XL";
         RomanMap[50] = "L";
         RomanMap[60] = "LX";
         RomanMap[70] = "LXX";
         RomanMap[80] = "LXXX";
         RomanMap[90] = "XC";

         RomanMap[1] = "I";
         RomanMap[2] = "II";
         RomanMap[3] = "III";
         RomanMap[4] = "IV";
         RomanMap[5] = "V";
         RomanMap[6] = "VI";
         RomanMap[7] = "VII";
         RomanMap[8] = "VIII";
         RomanMap[9] = "IX";

         RomanMap[0] = "";


        int qianwei = num / 1000;
        int baiwei = ( num - (qianwei * 1000) )/100 ;
        int shiwei = (num - (qianwei * 1000) - (baiwei * 100)) / 10;
        int gewei = num - (qianwei * 1000) - (baiwei * 100) - shiwei *10;
        string result = RomanMap[qianwei * 1000] + RomanMap[baiwei * 100] + RomanMap[shiwei * 10] + RomanMap[gewei];
        return result;
    }
};

 

12. Integer to Roman