Problem with C # code: revision numbers and letters

I am trying to write a function that takes a revision number (int) and turns it into a revision name (string). The formula should produce similar results:

  Number name
 1 A
 2 B
 3 C
 ... ...
 25 y
 26 Z
 27 AA
 28 AB
 29 AC
 ... ...
 51 AY
 52 AZ
 53 BA
 54 BB
 55 BC
 ... ...

It seems simple, but I think it might require recursion, and I'm terrible at that. Any suggestions?

+4
source share
5 answers

I think this is the same as generating an Excel column name from a column number:

private string GetExcelColumnName(int columnNumber) { int dividend = columnNumber; string columnName = String.Empty; int modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modulo).ToString() + columnName; dividend = (int)((dividend - modulo) / 26); } return columnName; } 
+6
source

I think you basically need to convert a number in a 10x number system to a number in a 26x number system.

For instance:

53 = 5 * 10 ^ 1 + 3 * 10 ^ 0 = [5] [3]

53 = B * 26 ^ 1 + A * 26 ^ 0 = [B] [A]


 int value10 = 53; int base10 = 10; string value26 = ""; int base26 = 26; int input = value10; while (true) { int mod = input / base26; if (mod > 0) value26 += Map26SymbolByValue10 (mod); // Will map 2 to 'B' else value26 += Map26SymbolByValue10 (input); // Will map 1 to 'A' int rest = input - mod * base26; if (input < base26) break; input = rest; } 
+5
source

I really hope this is not homework ... (unverified solution):

 if(value == 1) return "A"; StringBuilder result = new StringBuilder(); value--; while(value > 0) { result.Insert(0, 'A' + (value % 26)); value /= 26; } 

Recursive version based on tanascius original answer (also not verified):

 string ConvertToChar(int value) { char low = 'A' + (value - 1) % 26; if(value > 26) return ConvertToChar((value - 1) / 26 + 1) + low.ToString(); else return low.ToString(); } 
+2
source

Tested solution:

 private static string VersionName(int versionNum) { StringBuilder sb = new StringBuilder(); while (versionNum > 0) { versionNum--; sb.Insert(0, (char)('A' + (versionNum % 26))); versionNum /= 26; } return sb.ToString(); } 

I would not use recursion for this. Looping with StringBuilder is more efficient than concatenating strings with each recursion, although you probably need a crazy amount of fixes to notice the difference (4 letters are enough for more than 400,000 revisions).

+2
source

You can use the modulo operator and unit to get the code.
Like 55/26 == 2 (i.e. B) and 55% 26 = 3 (i.e. C). He works for two characters. When you have an unknown number of characters, you need to start a loop:

[look at Aaron's solution, mine was wrong)

+1
source

All Articles