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

13.Roman to Integer (Map)

时间:2015-07-23 21:32:56      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

Given a roman numeral, convert it to an integer.

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

class Solution {
public:
    int romanToInt(string s) {
        int values[] = {1000, 500, 100, 50, 10, 5, 1 };
        char numerals[] = {M, D, C, L, X, V, I };
        int i = 0, j = 0, result = 0;
        while(i < s.length()){
            if(s[i] != numerals[j]){
                j++;
                continue;
            }

            if(i+1<s.length() && j-1>=0 && s[i+1] == numerals[j-1]){
                result += values[j-1]-values[j];
                i+=2;
            }
            else if(i+1<s.length() && j-2>=0 && s[i+1] == numerals[j-2]){
                result += values[j-2]-values[j];
                i+=2;
            }
            else{
                result += values[j];
                i++;
            }
        }
        return result;
    }
};

 

13.Roman to Integer (Map)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4671714.html

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