My 32ms C++ solution


  • 1
    M
    class Solution {
    public:
        int romanToInt(string s) {
            int dic[26];
            dic['I'-'A']=1;
            dic['V'-'A']=5;
            dic['X'-'A']=10;
            dic['L'-'A']=50;
            dic['C'-'A']=100;
            dic['D'-'A']=500;
            dic['M'-'A']=1000;
            int result=dic[s[0]-'A'];
            char pre=s[0];
            string::size_type len=s.size();
            for(int i=1;i<len;i++)
            {
                result+=dic[s[i]-'A'];
                if(dic[s[i]-'A']>dic[pre-'A'])
                    result-=2*dic[pre-'A'];
                pre=s[i];
            }
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.