12. Integer to Roman
in LeetCode with 0 comment

12. Integer to Roman

in LeetCode with 0 comment

给于一个整型数字范围在1-3999,将它转化为罗马数字

题目

Integer to Roman

思路1

分类讨论,暴力解决。

class Solution {
public:
    string intToRoman(int num) {
        string res;
        //1000以上没那些幺蛾子
        if (num > 999) {
            for (int i = 0; i < num / 1000; i++) 
                res += 'M';
        }
        num %= 1000;

        //百位上的数字
        if (num / 100 == 4) {//400~499
            res += "CD";
        }else if (num / 100 == 9) {
            res += "CM";
        }else{
            if (num > 499) {
                res += 'D';
                num -= 500;
            }
            for (int i = 0; i < num / 100; i++)
                res += 'C';
        }
        num %= 100;

        //十位上的数字
        if (num / 10 == 4) {//40~49
            res += "XL";
        }
        else if (num / 10 == 9) {
            res += "XC";
        }
        else {
            if (num > 49) {
                res += 'L';
                num -= 50;
            }
            for (int i = 0; i < num / 10; i++)
                res += 'X';
        }

        num %= 10;

        //个位的数字

        if (num == 4) {
            res += "IV";
        }
        else if (num == 9) {
            res += "IX";
        }
        else {
            if (num > 4) {
                res += 'V';
                num -= 5;
            }
            for (int i = 0; i < num; i++)
                res += 'I';
        }

        return res;
    }
};

写完之后都有点怀疑自己。。。

略微洋气点的

把10个数字直接用罗马数字写出来

class Solution
{
public:
    string intToRoman(int num)
    {
        string one[11] = {"", "I","II","III","IV","V","VI","VII","VIII","IX"};          ///  个位
        string ten[11] = {"", "X", "XX","XXX","XL","L","LX","LXX","LXXX","XC"};         ///  十位
        string hundred[11] = {"", "C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};      ///  百位
        string thousand[4] = {"", "M", "MM","MMM"};                                     ///  千位



        string result = "";
        string* trans[4] = {one, ten, hundred, thousand};

        int index = 0;
        while (num > 0)
        {
            result = trans[index][num % 10] + result;
            num = num / 10;
            index++;
        }
        return result;
    }
};

其实也不算多么洋气的解法。。。

Responses

From now on, bravely dream and run toward that dream.
陕ICP备17001447号