12. 整数转罗马数字

廉价感情. 提交于 2020-01-30 05:13:41

leetcode12:12. 整数转罗马数字

题目描述

罗马数字包含以下七种字符: IVXLCDM

  • I 1
  • V 5
  • X 10
  • L 50
  • C 100
  • D 500
  • M 1000

Example

输入: 58
输出: "LVIII"
解释: L = 50, V = 5, III = 3

solution idea

暴力搜索
class Solution {
public:
/*
** 暴力搜索
*/
    string intToRoman(int num)
    {
        string result;
        vector<string> tmpVec1 = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        vector<string> tmpVec2 = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        vector<string> tmpVec3 = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        vector<string> tmpVec4 = {"", "M", "MM", "MMM"};
        vector<vector<string>> store = {tmpVec1, tmpVec2, tmpVec3, tmpVec4};
        result.append(store[3][num / 1000 % 10]); //千位
        result.append(store[2][num / 100 % 10]);  //百位
        result.append(store[1][num / 10 % 10]);	  //十位
        result.append(store[0][num % 10]);     //个位
        return result;
    }
};
贪心法
class Solution {
public:
/*
** 贪心法
*/
    string intToRoman(int num)
    {
        string result;
        vector<int> intGroup={1,4,5,9,10,40,50,90,100,400,500,900,1000};
        vector<string> strGroup={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
        while(num)
        {
            for(int i=intGroup.size()-1;i>=0;i--)
            {
                if (num>=intGroup[i])
                {
                    result.append(strGroup[i]);
                    num-=intGroup[i];
                    break;
                }
            }
        }
        return result;
    }
};

参考文献

  1. c++ prime 第5版
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!