[leetcode]Integer to Roman

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

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

posted on 2015-10-20 22:18  Mereyct  阅读(219)  评论(0编辑  收藏  举报

导航