C# solution using HashMap


  • 0
    S
        public int RomanToInt(string s) {
                int[] array = new int[16];
                int ctr = 0;
                int sum = 0;
                int prev = 0;
                Dictionary<char, int> HashMap = new Dictionary<char, int>();
                HashMap.Add('I', 1);
                HashMap.Add('V', 5);
                HashMap.Add('X', 10);
                HashMap.Add('L', 50);
                HashMap.Add('C', 100);
                HashMap.Add('D', 500);
                HashMap.Add('M', 1000);
                
                foreach (char c in s)
                {
                    if (ctr < 16)
                    {
                        if(HashMap[c]>prev && prev!=0){
                            sum -= 2*prev;
                        }
                            sum += HashMap[c];
                    }
                    else
                    {
                        return 0;
                    }
                    ctr++;
                    prev = HashMap[c];
                }
                return sum;
        }
    }

Log in to reply
 

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