Seems that there needs a C# solution


  • 0
    S

    Of course, this is not most efficient way since sorting on the keys can be avoided if using two arrays. But it should be slightly more readable.

         public string IntToRoman(int num)
            {
                var baseSymbols = new Dictionary<int, string>
                {
                    {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" }
                };
                var result = new StringBuilder();
                foreach(int key in baseSymbols.Keys.OrderByDescending(k => k))
                {
                    while (num >= key)
                    {
                        result.Append(baseSymbols[key]);
                        num -= key;
                    }
                    if (num < 1)
                        break;
                }
                return result.ToString();    
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.