Convert to integer vector and loop, simple c++ code


  • 0
    A

    First convert s into integer vector b with integer value of each symbol. Then scan from right to left if value increases add else subtract.

    class Solution {
    public:
        int romanToInt(string s) {
            vector<int> b;
            for(int i=0;i<s.size();i++)
            {
                if(s[i] == 'I')
                    b.push_back(1);
                if(s[i] == 'V')
                    b.push_back(5);
                if(s[i] == 'X')
                    b.push_back(10);
                if(s[i] == 'L')
                    b.push_back(50);
                if(s[i] == 'C')
                    b.push_back(100);
                if(s[i] == 'D')
                    b.push_back(500);
                if(s[i] == 'M')
                    b.push_back(1000);
            }
            int ans = b[s.size()-1];
            for(int i=s.size()-2;i >= 0;i--)
            {
                if(b[i] >= b[i+1])
                    ans += b[i];
                else
                    ans -= b[i];
            }
            return ans;
        }
    };

Log in to reply
 

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