我对 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
返回A
、26
返回Z
和27
返回AA
。“问题”是这个数字系统没有0,所以它不容易转换为任何基数。例如,如果A
为 0,那么AA
也将为 0,但事实并非如此。那么我该如何解决呢?