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.

分析:

罗马数字是由字符I,V,X,L,C,D,M等等表示的,其中
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;

经过分析发现,当字符所代表的的数字小于下一个字符所代表的的数字时,其值需要从总的数值里减去;别的情况是把其值累加到总的数值里去。

class Solution {
public:
    int romanToInt(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        map<char, int> myMap;
        myMap.insert(pair<char, int>('M',1000));
        myMap.insert(pair<char, int>('D', 500));
        myMap.insert(pair<char, int>('C', 100));
        myMap.insert(pair<char, int>('L', 50));
        myMap.insert(pair<char , int>('X', 10));
        myMap.insert(pair<char , int>('V', 5));
        myMap.insert(pair<char, int>('I',1));
        
        
        int n =s.size();
        int result  = myMap[s[n-1]];
        for(int i = 0 ; i< n-1 ; i++)
        {
           if(myMap[s[i]] >=myMap[s[i+1]])
           
              result += myMap[s[i]];
            else
              result -= myMap[s[i]];        
        }
        
        return result ;
    }
};
原文地址:https://www.cnblogs.com/graph/p/3209484.html