Roman to Integer

Q:Given a roman numeral, convert it to an integer.

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

A:首先建立字符到数字的map.其次,分析罗马数字组成的规则,从字符串后面往前看,如果

            if(dict[s[i+1]]>dict[s[i]])
                sum-=dict[s[i]];
            else
                sum+=dict[s[i]];
    int romanToInt(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s.empty())
            return 0;
        
        map<char,int> dict;
        
        dict['I'] = 1;
        dict['V'] = 5;
        dict['X'] = 10;
        dict['L'] = 50;
        dict['C'] = 100;
        dict['D'] = 500;
        dict['M'] = 1000;
        
        int n = s.size();
        
        int sum = dict[s[n-1]];
        for(int i=n-2;i>=0;i--)
        {
            if(dict[s[i+1]]>dict[s[i]])
                sum-=dict[s[i]];
            else
                sum+=dict[s[i]];
        }
        return sum;
        
    }

  

posted @ 2013-09-18 23:00  summer_zhou  阅读(170)  评论(0编辑  收藏  举报