Easy-to-understand O(n) C++ solution


  • 0
    M
    int romanToInt(string s) {
        int n = 0;
        int theI = 1, theX = 10, theC = 100;
        int len = (int)s.size();
        for(int i = len - 1; i >= 0; --i)
        {
            switch(s[i])
            {
                case 'I': { n += theI;} break;
                case 'V': { n += 5; theI = -1;} break;
                case 'X': { n += theX; theI = -1;} break;
                case 'L': { n += 50; theX = -10; } break;
                case 'C': { n += theC; theX = -10;} break;
                case 'D': { n += 500; theC = -100;} break;
                case 'M': { n += 1000; theC = -100;} break;
                default: { n = 0; return n;} break;
            }
        }
        return n;
    }

Log in to reply
 

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