Puzzle: Excel Column Number

12 Oct 2011 | By Mihai Roman | Tags google puzzle algorithms C/C++
Write a function (with helper functions if needed) called to Excel that takes an excel column value (A, B, C, D…AA, AB, AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=26..).

or another way of describing it:

Given the sequence S1 = {a,b,c,d,…,x,y,z,aa,ab,ac…. } and given that this sequence corresponds (term for term) to the sequence S2 = {1,2,3,4,….} Write code to convert an element of S1 to the corresponding element of S2. Write code to convert an element of S2 to the corresponding element of S1.
int excel(char* col) {
  int n = strlen(col);
  if (n < 1)
    return 0;
  int base = (int)('Z' - 'A');
  int result = col[n - 1] - 'A' + 1;
  for (int i = n - 2; i >= 0; i--) {
    result += (col[i] - 'A' + 1) * base;
    base *= base;
  }
  return result;  
}

blog comments powered by Disqus