C# single pass


  • 0
    H
    public int RomanToInt(string s) {
            Dictionary<char, int> map = new Dictionary<char, int>() {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500 }, {'M', 1000}};
            
            int sum = 0;
            for(int i = s.Length - 1; i >= 0; i--) {
                if (i < (s.Length - 1) && map[s[i]] < map[s[i + 1]]) sum -= map[s[i]];
                else sum += map[s[i]];
            }
            
            return sum;
        }
    

Log in to reply
 

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