leetcode[13]Roman to Integer

3256 ワード

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 len=s.length();

    if(len<1)return 0;

    map<char,int> maps;

    maps['I']=1;

    maps['V']=5;

    maps['X']=10;

    maps['L']=50;

    maps['C']=100;

    maps['D']=500;

    maps['M']=1000;

    int i=len-1;

    int res=maps[s[i]];

    while(i>0)

    {

        if(maps[s[i]]<=maps[s[--i]])

        {

            res+=maps[s[i]]; 

        }

        else

        {

            res-=maps[s[i]]; 

        }

    }

    return res;

    }

};