-3

Been given an exercise on converting roman numerals to integers in C#,i am still new to coding i am just stuck and confused on how to go on about this question. Given method and parameter as a start

    ```
    public int RomanToInt(string s){

    }
    ```

an example on how the answers should be

    ```
    Input: s = "III"
    Output: 3
    Explanation: III = 3.
    ```

1 Answers1

0

Something like this might work.

namespace RomanToNumbersAndReverse
{
    internal class RomanToNumber
    {
        public int RomanToInt(string s)
        {
            int sum = 0;
            Dictionary<char, int> romanNumbersDictionary = new()
            {
                { 'I', 1 },
                { 'V', 5 },
                { 'X', 10 },
                { 'L', 50 },
                { 'C', 100 },
                { 'D', 500 },
                { 'M', 1000 }
            };
            for (int i = 0; i < s.Length; i++)
            {
                char currentRomanChar = s[i];
                romanNumbersDictionary.TryGetValue(currentRomanChar, out int num);
                if (i + 1 < s.Length && romanNumbersDictionary[s[i + 1]] > romanNumbersDictionary[currentRomanChar])
                {
                    sum -= num;
                }
                else
                {
                    sum += num;
                }
            }
            return sum;
        }
    }
} 

source: https://www.c-sharpcorner.com/article/convert-roman-to-numbers-in-c-sharp/