29ms C++ solution


  • 0
    Y
    class Solution {
    public:
        int romanToInt(string s) {
            int res=0;
    //if smaller number appears before bigger number, take it away from the result, otherwise, just add them up
            for(int i=0; i<s.length(); i++) {
                switch(s[i]) {
                    case 'M': res+=1000; break;
                    case 'C': 
                        if(i+1!=s.length() && (s[i+1]=='D'||s[i+1]=='M'))
                            res-=100;
                        else res+=100;
                        break;
                    case 'D': res+=500; break;
                    case 'X': 
                        if(i+1!=s.length() && (s[i+1]=='L' || s[i+1]=='C'))
                            res-=10;
                        else res+=10;
                        break;
                    case 'L': res+=50; break;
                    case 'I': 
                        if(i+1!=s.length() && (s[i+1]=='V' || s[i+1]=='X'))
                            res-=1;
                        else res+=1;
                        break;
                    case 'V': res+=5; break;
                }
            }
            return res;
        }
    };

Log in to reply
 

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