首页 > 代码库 > 每日算法之十一:Integer to Roman

每日算法之十一:Integer to Roman

题目:Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

罗马表示方式如下:

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

其中每两个阶段的之间有一个减法的表示,比如900=CM, C写在M前面表示M-C。

范围给到3999,感觉情况不多直接打表其实更快,用代码判断表示估计比较繁琐。

然后就是贪心的做法,每次选择能表示的最大值,把对应的字符串连起来。 

穷举的方法:

class Solution {
public:
    string intToRoman(int num) {
        string roma = "";
        if(num/1000)
        {
            switch(num/1000)
            {
                case 1:
                    roma = roma+"M";
                    break;
                case 2:
                    roma = roma+"MM";
                    break;
                case 3:
                    roma = roma+"MMM";
                    break;
            }
        }
        num = num%1000;
        if(num/100)
        {
            switch(num/100)
            {
                case 1:roma = roma+"C";break;
                case 2:roma = roma+"CC";break;
                case 3:roma = roma+"CCC";break;
                case 4:roma = roma+"CD";break;
                case 5:roma = roma+"D";break;
                case 6:roma = roma+"DC";break;
                case 7:roma = roma+"DCC";break;
                case 8:roma = roma+"DCCC";break;
                case 9:roma = roma+"CM";break;
            }
        }
        num = num%100;
        if(num/10)
        {
            switch(num/10)
            {
                case 1:roma = roma+"X";break;
                case 2:roma = roma+"XX";break;
                case 3:roma = roma+"XXX";break;
                case 4:roma = roma+"XL";break;
                case 5:roma = roma+"L";break;
                case 6:roma = roma+"LX";break;
                case 7:roma = roma+"LXX";break;
                case 8:roma = roma+"LXXX";break;
                case 9:roma = roma+"XC";break;
            }
        }
        num = num%10;
        switch(num)
        {
                case 1:roma = roma+"I";break;
                case 2:roma = roma+"II";break;
                case 3:roma = roma+"III";break;
                case 4:roma = roma+"IV";break;
                case 5:roma = roma+"V";break;
                case 6:roma = roma+"VI";break;
                case 7:roma = roma+"VII";break;
                case 8:roma = roma+"VIII";break;
                case 9:roma = roma+"IX";break;
        }
        return roma;
    }
};

遍历实现的方法:

class Solution {
public:
    string intToRoman(int num) {
        string str;  
        string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};  
        int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1}; 
        for(int i=0;num!=0;++i)
        {
            while(num>=value[i])
            {
                num-=value[i];
                str+=symbol[i];
            }
        }
        return str;
    }
};