[力扣] 算法 12 (C#)

12. 整数转罗马数字

一开始我是这样写的:

public class Solution
{
    public string IntToRoman(int num)
    {
        return new string[] { null, "M", "MM", "MMM" }[num / 1000] +
            Pattern('C', 'D', 'M')[num / 100 % 10] +
            Pattern('X', 'L', 'C')[num / 10 % 10] +
            Pattern('I', 'V', 'X')[num % 10];
    }
    /*
     * 1 a
     * 2 aa
     * 3 aaa
     * 4 ab
     * 5 b
     * 6 ba
     * 7 baa
     * 8 baaa
     * 9 ac
     */
    public static string[] Pattern(char a, char b, char c)
    {
        var ret = new string[10];
        ret[4] = string.Concat(a, b);
        ret[9] = string.Concat(a, c);
        for (var i = 5; i <= 8; i++)
            ret[i] += b;
        for (var i = 1; i <= 3; i++)
        {
            for (var j = 0; j < i; j++)
            {
                ret[i] += a;
                ret[i + 5] += a;
            }
        }
        return ret;
    }
}

看评论区里有贪心的解法,故用这种解法再做一遍:

public class Solution {
    readonly (int, string)[] pattern = new (int, string)[] {
        (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 string IntToRoman(int num)
    {
        var index = 0;
        var ret = string.Empty;
        while (index < pattern.Length)
        {
            if (num >= pattern[index].Item1)
            {
                num -= pattern[index].Item1;
                ret += pattern[index].Item2;
            }
            else
            {
                index++;
            }
        }
        return ret;
    }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注