My 54ms C++ solution


  • 0
    E

    The core idea is that if the currently processing Roman number is greater than the last Roman number, we should subtract the last Roman number twice.

    int romanToInt(string s) 
    {
        int ret = 0;
        int last = INT_MAX;  //the last Roman number in s
        for(auto it=s.begin(); it!=s.end(); ++it)
        {
            int num = convert(*it);
            ret += num;
            //trick here
            if(num > last)
                ret -= 2 * last;
            last = num;
        }
        return ret;
    }
    int convert(char c)
    {
        switch(c)
        {
        case 'M': return 1000;
        case 'D': return 500;
        case 'C': return 100;
        case 'L': return 50;
        case 'X': return 10;
        case 'V': return 5;
        case 'I': return 1;
        default : return 0;
        }
    }

Log in to reply
 

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