LeetCode:Roman to Integer

Given a roman numeral, convert it to an integer.

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

// Source : https://oj.leetcode.com/problems/roman-to-integer/
// Author : Chao Zeng
// Date   : 2014-12-20

//罗马字母的转化有点恶心。。。看wikipedia才懂
class Solution {
public:
    int romanToInt(string s) {
        map<char,int> m;
        m['I'] = 1;
        m['V'] = 5;
        m['X'] = 10;
        m['L'] = 50;
        m['C'] = 100;
        m['D'] = 500;
        m['M'] = 1000;
        int ans = 0;
        int length = s.length();
        for (int i = length - 1; i >= 0; i--){
            if (i == length - 1){
                ans = m[s[i]];
                continue;
            }
            if (m[s[i]] >= m[s[i+1]])
                ans += m[s[i]];
            else
                ans -= m[s[i]];
        }
        return ans;
    }
};



版权声明:本文为hnuzengchao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。