码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Integer to Roman

时间:2015-10-20 22:47:28      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
class Solution {
public:
    string intToRoman(int num) {
        string a[10] = {"","I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        string b[10] = {"","X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        string c[10] = {"","C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        string d[10] = {"","M", "MM", "MMM"};
        
        string res = "";
        int i = num;
        int temp;
        int tm[5];
        memset(tm,-1,sizeof(int)*5);
        int j = 0;
        while(i != 0)
        {
            temp = i % 10;
            i = i /10;
            j++;
            tm[j] = temp;
           
        }
        for(int k = 4; k > 0; k--)
        {
            if(tm[k] == -1) continue;
            if(k == 4) res += d[tm[k]]; 
            if(k == 3) res += c[tm[k]];
            if(k == 2) res += b[tm[k]];
            if(k == 1) res += a[tm[k]]; 
        }
        
        return res;
    }
};



/*1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.*/
View Code

比较简单,看代码就明白了。

[leetcode]Integer to Roman

标签:

原文地址:http://www.cnblogs.com/yusenwu/p/4896266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!