Leetcode 12 13 整数转罗马数字 罗马数字转整数

在这里插入图片描述

整数转罗马数

在这里插入图片描述
参考:http://www.cnblogs.com/grandyang/p/4123374.html
因为有左边字符对应数字值小于右边字符对应的数字值的情况,所以相对麻烦一点。为了避免这种麻烦,将各种情况保存在一个数组型数据中,历遍这个vector来实现。具体直接看程序。

class Solution {
public:
    string intToRoman(int num) {
        string res;
        if(num>3999 || num<1) return res;
        vector<int> data1{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> roma{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        for(int i=0;i<data1.size();++i)
        {
            if(data1[i]>num) continue;
            while(data1[i]<=num)
            {
                num-=data1[i];
                res+=roma[i];
            }
        }
        return res;
    }
};

罗马数转整数

在这里插入图片描述
罗马数转整数的思路很清楚,历遍这个罗马字符串,对一个位置的字符,如果它对应的数字值大于它后面的字母的数字值,那么说明要减去该值。其他情况要加上该值。

class Solution {
public:
    int romanToInt(string s) {
        int res=0;
        map<char,int> m{{'I',1}, {'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        for(int i=0;i<s.size();++i)
        {
            if(i<s.size()-1 && m[s[i+1]] >m[s[i]]) res-=m[s[i]];
            else res+=m[s[i]];
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/yuanliang861/article/details/84782591