-2

I was expecting 3 when entering III but I keep on getting 1 and the funny thing is i think it is only happening with a combination of the same roman letters because II is giving me back 2 like i wanted LVIII is giving me 56 instead of 58, but MCMXCIV is giving me back 1994.

public class Solution
{
    public int RomanToInt(string s)
    {
        if (s.Length == 1)
        {
            if (s == "I")
            {
                return 1;
            }
            else if (s == "V")
            {
                return 5;
            }
            else if (s == "X")
            {
                return 10;
            }
            else if (s == "L")
            {
                return 50;
            }
            else if (s == "C")
            {
                return 100;
            }
            else if(s == "D")
            {
                return 500;
            }
            else
            {
                return 1000;
            }
        }
        else if (s.Length > 0 )
        {
            if (RomanToInt(s[0].ToString()) < RomanToInt(s.Substring(1, s.Length - 1).ToString()))
            {
                return RomanToInt(s.Substring(1, s.Length -1).ToString()) - RomanToInt(s[0].ToString());
            }
            else
            {
               return (RomanToInt(s[0].ToString())) + RomanToInt(s.Substring(1, s.Length - 1).ToString());
            }
        }
        else
        {
            return 0;
        }
    }
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
WeirdPanda
  • 13
  • 1
  • 2
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Filburt Jun 11 '23 at 09:08

2 Answers2

0

The problem is where you test if the value for the first character is smaller than de value for the rest of the string:

If you input "III" then the value for the first character is 1, and the value for the second part ("II") is 2. Your code then subtracts 1 from 2 yielding a result of 1.

Your Logic should take into account that a repetition of characters in a Roman Numerical means the individual values should be added. Substraction only happens when the following character (not 'substring') has a value greater than the preceding one.

Johan Donne
  • 3,104
  • 14
  • 21
0

The problem is where you test if the value for the first character is smaller than de value for the rest of the string:

If you input "III" then the value for the first character is 1, and the value for the second part ("II") is 2. Your code then subtracts 1 from 2 yielding a result of 1.

Your Logic should take into account that a repetition of characters in a Roman Numerical means the individual values should be added. Substraction only happens when the following character (not substring) has a value greater than the preceding one.

Johan Donne
  • 3,104
  • 14
  • 21