Converting integers to roman numerals

前端 未结 29 2403
走了就别回头了
走了就别回头了 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:57

    A string representation of the number's corresponding roman numeral.

        public static string ToRomanNumeral(this int number)
        {
    
            var retVal = new StringBuilder(5);
            var valueMap = new SortedDictionary
                               {
                                   { 1, "I" },
                                   { 4, "IV" },
                                   { 5, "V" },
                                   { 9, "IX" },
                                   { 10, "X" },
                                   { 40, "XL" },
                                   { 50, "L" },
                                   { 90, "XC" },
                                   { 100, "C" },
                                   { 400, "CD" },
                                   { 500, "D" },
                                   { 900, "CM" },
                                   { 1000, "M" },
                               };
    
            foreach (var kvp in valueMap.Reverse())
            {
                while (number >= kvp.Key)
                {
                    number -= kvp.Key;
                    retVal.Append(kvp.Value);
                }
            }
    
            return retVal.ToString();
        }
    

提交回复
热议问题