C++ solution from right to left


  • 0
    L

    The key is from right to left,

    example: XCIX

    1. X=10
    2. IX = 9
    3. C=100
    4. XC = 90
    5. XCIX=99
    int romanToInt(string s) {
            
            map<char, int> m = {{'I',1},{'V',5}, {'X',10},{'L',50},{'C',100}, {'D',500},{'M',1000}};    
            
            int sum = 0;
            int len = (int)s.size();
            for (int i=len-1; i>=0;i--)
            {
                if (i == len-1 || m[s[i]] >= m[s[i+1]])
                {
                    sum += m[s[i]];
                }
                
                else 
                {
                    sum -= m[s[i]];
                }
                
            }
            
            return sum;
        }
    

Log in to reply
 

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