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

Roman to Integer

时间:2015-02-06 23:10:02      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

  这道题很简单,我就直接贴答案了。

solution1:

int romanToInt(string s) {
    int res = 0;
    char ch;
    int n = s.size();
    s += "#";
    for (int i = 0;i < n;++i)
    {
        ch = s[i];
        switch(ch){
        case I:
            if(s[i+1] == V || s[i+1] == X)
                res -= 1;
            else
                res += 1;
            break;
        case V:
            res += 5;
            break;
        case X:
            if(s[i+1] == L || s[i+1] == C)
                res -= 10;
            else
                res += 10;
            break;
        case L:
            res += 50;
            break;
        case C:
            if(s[i+1] == D || s[i+1] == M)
                res -= 100;
            else
                res += 100;
            break;
        case D:
            res += 500;
            break;
        case M:
            res += 1000;
            break;
        default:
            break;
        }
    }
    return res;
}

上面是我自己写的,下面用了map,代码看起来简洁些。
solution2:

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

 

Roman to Integer

标签:

原文地址:http://www.cnblogs.com/gattaca/p/4278057.html

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