Solution of the Problem in C#


  • 0
    P
            public int RomanToInt(string s)
            {
                // All the valid characters in Roman with their values.
                Dictionary<char, int> precedenceValues = new Dictionary<char, int>();
                precedenceValues.Add('I', 1);
                precedenceValues.Add('V', 5);
                precedenceValues.Add('X', 10);
                precedenceValues.Add('L', 50);
                precedenceValues.Add('C', 100);
                precedenceValues.Add('D', 500);
                precedenceValues.Add('M', 1000);
                // convert the input into uppper string
                s = s.ToUpper();
    
                List<int> values = new List<int>();
                int total = 0;
                char lastChar = ' ';
                int val = 0;
    
                // loop from the end of the string till the 0 index
                for (int i = s.Length - 1; i >= 0; i--)
                {
                    char c = s[i];
                    // check if the character is valid roman value
                    if (precedenceValues.ContainsKey(c))
                    {
                        // if this is first chacacter 
                        if (string.IsNullOrEmpty(lastChar.ToString().Trim()))
                        {
                            // get the value of the character
                            val = precedenceValues[c];
                        }
                        // if current number has smaller value than the last character
                        else if (precedenceValues[lastChar] > precedenceValues[c])
                        {
                            // subtract the current value from the val.
                            val = val - precedenceValues[c];
                        }
                        else // current character value is greater or equals the the last character value
                        {
                            // add the val into the list
                            values.Add(val);
                            // assign the current character value to the val.
                            val = precedenceValues[c];
                        }
                        // save the current character as last character for next iteration.
                        lastChar = c;
                    }
                    else
                    {
                        // invalid roman string
                        return 0;
                    }
                }
    
                // add the last val to the list
                values.Add(val);
    
                // sum all the values in the list to get the final total
                foreach (int i in values)
                {
                    total += i;
                }
    
                return total;
            }
    

Log in to reply
 

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