关闭

[LeetCode] Roman to Integer

178人阅读 评论(0) 收藏 举报
分类:

使用map

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

    }
};

c语言同样的思路

int romanToInt(char *s) {
#define _M 1000
#define _D 500
#define _C 100
#define _L 50
#define _X 10
#define _V 5
#define _I 1

    int result  = 0;
    int i;
    int last = _M;
    for(i = 0;i < strlen(s);i++)
    {
        switch (s[i])
        {
            case 'M':
                result = (last >= _M ? result + _M:result + _M - (last << 1));
                last = _M;        
            break;
            case 'D':
                result = (last >= _D ? result + _D:result + _D - (last << 1));
                last = _D;
            break;
            case 'C':
                result = (last >= _C ? result + _C:result + _C - (last << 1));
                last = _C;
            break;
            case 'L':
                result = (last >= _L ? result + _L:result + _L - (last << 1));
                last = _L;
            break;
            case 'X':
                result = (last >= _X ? result + _X:result + _X - (last << 1));
                last = _X;
            break;
            case 'V':
                result = (last >= _V ? result + _V:result + _V - (last << 1));
                last = _V;
            break;
            case 'I':
                result = (last >= _I ? result + _I:result + _I - (last << 1));
                last = _I;
            break;
        }

    }
    return result;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55684次
    • 积分:2171
    • 等级:
    • 排名:第17446名
    • 原创:162篇
    • 转载:9篇
    • 译文:0篇
    • 评论:13条
    文章分类
    最新评论