0

I try to convert my function, which uses an RomanNumeral Input to output it as Decimal Value, from JS into C#, but somehow im stuck and really need advice on how to make this Work.

using System;
using System.Collections.Generic;

class solution
{

static int romanToDecimal(string romanNums)
{
    int result = 0; 
    int [] deci = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    string [] roman = {"M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I"};

    for (var i = 0; i < deci.Length; i++)
    {   
        while (romanNums.IndexOf(roman[i]) == 0) 
        {
            result += deci[i]; 

            romanNums = romanNums.Replace(roman[i], " "); 
        }                                               
    }                                                   
    return result;                                  
}

static void Main()
{

Console.WriteLine(romanToDecimal("V")); //Gibt 5 aus.
Console.WriteLine(romanToDecimal("XIX")); // Gibt 19 aus.
Console.WriteLine(romanToDecimal("MDXXVI"));// Gibt 1526 aus.
Console.WriteLine(romanToDecimal("MCCCXXXVII"));// Gibt 1337 aus.
}

}
3
  • 1
    Please explain why the current code doesn't work Commented May 28, 2017 at 23:59
  • I don't think XD is 90. Commented May 29, 2017 at 1:16
  • It should be XC instead Commented May 29, 2017 at 1:18

1 Answer 1

2

Replace works differently in C#, use substring to remove the first few characters matching:

    static int romanToDecimal(string romanNums)
    {
        int result = 0;
        int[] deci = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        string[] roman = { "M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I" };

        for (var i = 0; i < deci.Length; i++)
        {
            while (romanNums.IndexOf(roman[i]) == 0)
            {
                result += deci[i];

                romanNums = romanNums.Substring(roman[i].Length);
            }
        }
        return result;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.