Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to Roman Format

Tags:

c#

asp.net

I am trying to get the roman numbers from 0-50. I just write the integer number on the textbox and press the button and I want to have its roman format in the label.

I have written the code and it works very well from 0-50 numbers.

But, I think that the solution which I have is not optimal.

Can anyone please help me, how can I make it more optimal.

int number = Convert.ToInt32( tb_input.Text);
            StringBuilder sb = new StringBuilder();      
            sb= IntToRoman(number, sb);



       Label1.Text =sb.ToString();


public StringBuilder IntToRoman(int number, StringBuilder sb)
    {
        int flag = 0;
        if (number >= 50 && flag==0)
        {
            sb.Append("L");
            IntToRoman(number - 50, sb);
            flag = 1;
        }
        if (number >= 10 && flag == 0)
        {
            sb.Append("X");
            IntToRoman(number - 10, sb);
            flag = 1;

        }
        if (number >= 9 && flag == 0)
        {
            sb.Append("IX");
            IntToRoman(number - 9, sb);
            flag = 1;
        }

        if (number >= 5 && flag == 0)
        {
            sb.Append("V");
            IntToRoman(number - 5, sb);
            flag = 1;
        }
        if (number >= 4 && flag == 0)
        {
            sb.Append("IV-");
            IntToRoman(number - 4, sb);
            flag = 1;
        }

        if (number >= 1 && flag == 0)
        {
            sb.Append("I");
            IntToRoman(number - 1, sb);
            flag = 1;
        }

        if (number ==0)
        {            
            return sb;

        }
        return sb;
    }
like image 303
user3417746 Avatar asked Aug 09 '26 01:08

user3417746


1 Answers

Pretty straightforward code and works for any number...

    public static List<string> romanNumerals = new List<string>() { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
    public static List<int> numerals = new List<int>() { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };

    public static string ToRomanNumeral(int number)
    {
        var romanNumeral = string.Empty;
        while (number > 0)
        {
            // find biggest numeral that is less than equal to number
            var index = numerals.FindIndex(x => x <= number);
            // subtract it's value from your number
            number -= numerals[index];
            // tack it onto the end of your roman numeral
            romanNumeral += romanNumerals[index];
        }
        return romanNumeral;
    }

Usage...

ToRomanNumeral(58) = 'LVIII'
ToRomanNumeral(2014) = 'MMXIV'
like image 105
Kevin Avatar answered Aug 10 '26 15:08

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!