C++ Solution


  • 0
    O
    // Helper function
    int SingleLetterToInt(const char c)
    {
        switch(c)
        {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default:
                return -1;
        }
    }
    
    int romanToInt(string s) {
        int res = 0;
        int prev = -1; // previous roman number letter
        for (std::size_t i = 0; i < s.size(); ++i)
        {
            int t = SingleLetterToInt(s[i]);
            if (prev != -1 && t > prev) // If previous number is smaller current letter, like IV (4), we need to
                                        // subtract it out instead. Since we already added it, we need to subtract
                                        // it twice. Using bitwise left shift is faster than multiply.
            {
                res -= prev << 1;
            }
            res += t;
            prev = t;
        }
        return res;
    }

Log in to reply
 

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