My clean c++ code with unordered_map


  • 0
    S
     /***************************
     * author : s2003zy
     * weibo  : weibo.com/songzy982
     * ************************/
    class Solution {
    public:
        int romanToInt(string s) {
            static unordered_map<char, int> hash{{'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}};
            int res = 0;
            for (int i = 0; i < s.size(); i++) {
                if (i > 0 && hash[s[i]] > hash[s[i - 1]]) {
                    res += hash[s[i]] - 2 * hash[s[i - 1]];
                } else {
                    res += hash[s[i]];
                }
            }
            return res;
        }
    };

Log in to reply
 

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