Find Excel column number from column title in C++

C++Server Side ProgrammingProgramming

We know that the excel column numbers are alphabetic. It starts from A, and after Z, it will AA, AB, to ZZ, then again AAA, AAB, to ZZZ and so on. So column 1 is A, column 27 is Z. Here we will see how to get the column letter if number of column is given. So if the column number is 80, then it will be CB.

Suppose we have a number n, and its value is 28, then we need to take reminder with 26. If the remainder is 0, then the number is 26, 52 and so on. Then we put Z in the output string. The value of n becomes n/26 – 1. And if the remainders are non-zero then we need to just insert the character accordingly into the string, and do n = n/26. Finally the reverse of the string will be printed.

Example

#include<iostream>
#include<algorithm>
using namespace std;
void showColumnLetters(int n) {
   string str = "";
   while (n) {
      int rem = n%26;
      if (rem==0) {
         str += 'Z';
         n = (n/26)-1;
      }
      else{
         str += (rem-1) + 'A';
         n = n/26;
      }
   }
   reverse(str.begin(), str.begin() + str.length());
   cout << str << endl;
}
int main() {
   int n = 700;
   cout << "Cell name of " << n << " is: ";
   showColumnLetters(700);
}

Output

Cell name of 700 is: ZX
raja
Published on 01-Nov-2019 07:21:57
Advertisements