Converting integers to roman numerals

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

    One more straight forward solution. Trying to improve slightly the performance I use StringBuilder, iterate through less keys (one the other site of course LINQ-where might add additional delay)

    public class ArabicToRomanConverter
    {
        private static readonly Dictionary _romanDictionary = new Dictionary
        {
            {1000,"M"},
            {900,"CM"},
            {500,"D"},
            {400,"CD"},
            {100,"C"},
            {90,"XC"},
            {50,"L"},
            {40,"XL"},
            {10,"X"},
            {9,"IX"},
            {5,"V"},
            {4,"IV"},
            {1 ,"I"}
        };
    
        public ArabicToRomanConverter()
        {
    
        }
    
        public string Convert(int arabicNumber)
        {
            StringBuilder romanNumber = new StringBuilder();
            var keys = _romanDictionary.Keys.Where(k => arabicNumber >= k).ToList();
            for (int i = 0; i < keys.Count && arabicNumber > 0; i++)
            {
                int ckey = keys[i];
                int division = arabicNumber / ckey;
                if (division != 0)
                {
                    for (int j = 0; j < division; j++)
                    {
                        romanNumber.Append(_romanDictionary[ckey]);
                        arabicNumber -= ckey;
                    }
                }
            }
    
            return romanNumber.ToString();
        }
    }
    

提交回复
热议问题