How is this iterative solution?


  • 0
    S

    Hi,

    I am new here. Can you tell me how is the following iterative solution? I tend to write dirty code.

    class Solution {
    public:
        map<char,int> m,v;
        int romanToInt(string s)
        {
            m['F']=1001;
            m['M']=1000;
            m['D']=500;
            m['C']=100;
            m['L']=50;
            m['X']=10;
            m['V']=5;
            m['I']=1;
            v['M']=0;
            v['D']=0;
            v['C']=0;
            v['L']=0;
            v['X']=0;
            v['V']=0;
            v['I']=0;
            
            char prev='F';
            int temp;
            for(string::iterator it=s.begin();it!=s.end();it++)
            {
                temp=m[*it];
                if(temp>m[prev])
                    v[prev]*=-1;
                v[*it]+=m[*it];
                prev=*it;
            }
            int sum=0;
            for(map<char,int>::iterator it=v.begin();it!=v.end();it++)
                sum+=it->second;
            return sum;
        }
    };

Log in to reply
 

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