[C++] Clean solution with explanation


  • 0
    S
    class Solution {
    public:
        int romanToInt(string s) {
            std::map<char, int> translate {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
            int lastValue = 0;
            int total = 0;
            for (auto digit : s) {
                auto currentValue = translate[digit];
                if (lastValue < translate[digit]) {
                    total += currentValue - 2*lastValue;
                } else {
                    total += currentValue;
                }
                
                lastValue = currentValue;
            }
            
            return total;
        }
    };
    

    An initializer list is used to setup the mapping from Roman Numeral to value. From there, you keep adding each digit's value until the previous digit was less than the value of the next digit, which means you need to remove the last addition (since it's being subtracted now) and also subtract it from the current digit.


Log in to reply
 

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