A C++ solution


  • 0
    W
    class Solution {
    public:
        int romanToInt(string s) 
        {
            int n=0, lastnn=0;
            for(auto it=s.rbegin(); it != s.rend(); ++it)
            {
                char c = *it;
                int nn;
                if(c == 'I')
                    nn =1;
                else if(c == 'V')
                    nn =5;
                else if(c == 'X')
                    nn =10;
                else if(c == 'L')
                    nn =50;
                else if(c == 'C')
                    nn =100;
                else if(c == 'D')
                    nn =500;
                else if(c == 'M')
                    nn =1000;
                
                n += lastnn > nn ? -nn : nn;            
                lastnn=nn;            
            }     
            return n;
        }
    };
    

Log in to reply
 

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