2

我对 C# 中的自定义数字系统有一个要求,如下所示:

A - 1
B - 2
...
Z - 26
AA - 27
AB - 28

我制作了一个函数,可以将任意字符串转换为这样的数字:

    private const int Min = 'A';
    private const int Max = 'Z';
    private const int Base = Max - Min + 1;

    private static int GetCharValue(char c)
    {
        if (c < Min || c > Max)
            throw new ArgumentOutOfRangeException(nameof(c), c, $"Character needs to be between '{Min}' and '{Max}', was '{c}'.");

        return c - Min + 1;
    }

    public static int GetStringValue(string s)
    {
        char[] chars = s.ToCharArray();
        int[] values = new int[chars.Length];
        for (var i = 0; i < chars.Length; i++)
        {
            values[i] = GetCharValue(chars[i]);
        }

        int position = 1;
        int value = 0;
        for (var i = values.Length - 1; i >= 0; i--)
        {
            value += position * values[i];
            position *= Base;
        }

        return value;
    }

我已经对其进行了测试,可以达到最高AAA(不严格,只是略过打印它们的输出)。但是,我一生都无法弄清楚如何编写反向函数。换句话说,我需要1返回A26返回Z27返回AA。“问题”是这个数字系统没有0,所以它不容易转换为任何基数。例如,如果A为 0,那么AA也将为 0,但事实并非如此。那么我该如何解决呢?

4

1 回答 1

0

你可以像这样简单地生成它....

    public static IEnumerable<string> generate()
    {
        long n = -1;
        while (true) yield return toBase26(++n);
    }

    public static string toBase26(long i)
    {
        if (i == 0) return ""; i--;
        return toBase26(i / 26) + (char)('A' + i % 26);
    }



    public static void BuildQuery()
    {
        IEnumerable<string> lstExcelCols = generate();
        try
        {

            string s = lstExcelCols.ElementAtOrDefault(1) ;
        }
        catch (Exception exc)
        {

        }


    }
于 2017-07-25T13:06:30.343 回答