C++ Very Simple Solution

  • 0

    The goal here is to keep things very simple, it can be optimized. Still, performance beats ~74%.
    This solution assumes the input is well-formed.

    Step 1: Create an associative mapping between roman numeral values and decimal values.
    Step 2: Iterate backwards across transcoded values (adding roman numerals right to left).
    Step 3: When the previous value is greater, this is a subtraction case (such as IX = [10-1] = 9). Otherwise, sum.
    Step 4: Record previous value, so we can later check for a subtractive case.

        int romanToInt(string s)
            unordered_map<char, int> rToI{  
            int sum = 0, len = s.length(), pre = INT_MIN, v = 0;
            for( int i = len-1; i >= 0; --i )
                v = rToI[s[i]];
                sum += (v >= pre) ? v : -v;
                pre = v;
            return sum;

Log in to reply

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