首页 > 其他 > 详细

13.Roman to Integer (Map)

时间:2015-07-23 21:32:49      阅读:223      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!