Converting integers to roman numerals

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

    This should be the simplest solution.

    public string IntToRoman(int num)
    {
        var result = string.Empty;
        var map = new Dictionary
        {
            {"M", 1000 },
            {"CM", 900},
            {"D", 500},
            {"CD", 400},
            {"C", 100},
            {"XC", 90},
            {"L", 50},
            {"XL", 40},
            {"X", 10},
            {"IX", 9},
            {"V", 5},
            {"IV", 4},
            {"I", 1}
        };
        foreach (var pair in map)
        {
            result += string.Join(string.Empty, Enumerable.Repeat(pair.Key, num / pair.Value));
            num %= pair.Value;
        }
        return result;
    }
    

提交回复
热议问题