Converting integers to roman numerals

前端 未结 29 2533
走了就别回头了
走了就别回头了 2020-12-02 09:16

I\'m trying to write a function that converts numbers to roman numerals. This is my code so far; however, it only works with numbers that are less than 400. Is there a quick

29条回答
  •  一个人的身影
    2020-12-02 09:55

    Here's my effort, built with extension in mind and hopefully easy to understand, probably not the fastest method though. I wanted to complete this as got as part of interview test(which was very demoralising), requires an understanding of the problem first though in order to tackle it.

    It should do all numbers, can be checked on here https://www.calculateme.com/roman-numerals/from-roman

            static void Main(string[] args)
        {
    
            CalculateRomanNumerals(1674);
        }
    
        private static void CalculateRomanNumerals(int integerInput)
        {
            foreach (var item in Enum.GetValues(typeof(RomanNumerals)).Cast().Reverse())
            {
                integerInput = ProcessNumber(integerInput, item);
            }
    
            Console.ReadKey();
        }
    
        private static int ProcessNumber(int input, int number)
        {
            while (input >= number)
            {
                input -= number;
                Console.Write((RomanNumerals)number);
            }
    
            return input;
        }
    
        enum RomanNumerals : int
        {
            I = 1,
            IV = 4,
            V = 5,
            IX = 9,
            X = 10,
            L = 50,
            XC = 90,
            C = 100,
            CD = 400,
            D = 500,
            CM = 900,
            M = 1000
        }
    

提交回复
热议问题