2017-07-25 58 views
2

我在C#中自定义数字系统都按以下要求:自定义数字系统在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,但事实并非如此。那么我该如何解决这个问题?

+2

...或者'AAA'是'703'? –

+0

它看起来像你试图创建一个base_n数字系统......但我不认为'AA'应该代表你认为它的作用 – Kritner

+0

“问题”是你的数字系统确实有一个零,但它不一致。这是一个奇怪的不是真正的定位系统。在'AA'中,第一个'A'是一个,而第二个'A'是零。 “AAA”是指011,010,100,101,110 ...?实际需求是什么,只是客户的一些模糊的期望,并不真正知道他想要什么?还是你想复制Excel的坐标系? – Luaan

回答

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) 
     { 

     } 


    }