美文网首页LeetCode蹂躏集
2018-07-03 12. Integer to Roman

2018-07-03 12. Integer to Roman

作者: alexsssu | 来源:发表于2018-07-03 13:46 被阅读0次

    题意:给你一个数字,转换成罗马数字,需要遵循罗马数字排布的一些规则。
    解题思路:
    思路一:因为9和4比较特殊,其余的就是直接累计,可以把罗马数字分成9,5,4,1的对应表,然后逐一遍历将对应的罗马符号放入该位即可。

    class Solution {
    public:
        string intToRoman(int num) {
            string ans;
            
            vector<vector<string>> ivec;      
            vector<string> ivec1 = {"IX","V","IV","I"};
            vector<string> ivec2 = {"XC","L","XL","X"};
            vector<string> ivec3 = {"CM","D","CD","C"};
            vector<string> ivec4 = {"  "," ","  ","M"};
            ivec.push_back(ivec1);
            ivec.push_back(ivec2);
            ivec.push_back(ivec3);
            ivec.push_back(ivec4);
            
            int a[4] = {9, 5, 4, 1};
            int bt = 0;
            while(num){
                int n = num % 10;
                string ss;
                while(n){
                    for(int i = 0; i < 4; i++){
                        //cout << a[i]  << endl;
                        if(n >= a[i]){
                            ss += ivec[bt][i];
                            n -= a[i];
                        }
                    }
                }
                ans = ss + ans;
                num /= 10;
                bt++;
            }
            return ans;
        }
    };
    

    思路二:由于题目给出条件,说数字不会超过3999,直接暴力更快更准确。

    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", "", "", "", "", "", ""};
            return d[num/1000] + c[(num/100)%10] + b[(num/10)%10] + a[num%10]; 
        }
    };
    

    真 * 牛逼!

    相关文章

      网友评论

        本文标题:2018-07-03 12. Integer to Roman

        本文链接:https://www.haomeiwen.com/subject/lziduftx.html