c++excel

Figuring out the number corresponding to a letter of the alphabet?


I'm trying to duplicate the way excel provides labels its columns where

A = 1
B = 2

so on and so forth, so that it eventually reaches

AB
AC
AD

etc, etc.

How do I algorithmically take a number (like 52) and convert it to its equivalent alphabet representation?


Solution

  • string get(int a) {
      a--; // Reduce by one to make the values with 1 letter 0..25, 
           // with two - 26.. 26^2-1 and so on
      int val = 0; // number of columns with no more then given number of letters
      int number = 0;
      while (val < a) {
        val = val*26 + 26;
        number++;
      }
      val = (val - 26)/26;
      a -= val; // subtract the number of columns with less letters 
      string res;
      for (int i = 0; i < number; ++i) {
        res.push_back(a%26 + 'A');
        a /= 26;
      }
      reverse(res.begin(), res.end());
      return res;
    }
    

    Hope that helps.