Find Excel column number from column title

Given a column title as appears in an Excel sheet, return its corresponding column number.

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 

Examples:

Input : A
Output : 1

Input : AA
Output : 27

The process is similar to binary to decimal conversion. For example to convert AB, we do 26 * 1 + 2. As another example, to convert CDA, we do 3*26*26 + 4*26 + 1

// C++ program to return title to resul
// of excel sheet.
#include <bits/stdc++.h>
using namespace std;
// Returns resul when we pass title.
int titleToNumber(string s)
{
    // This process is similar to binary-to-
    // decimal conversion
    int result = 0;
    for (const auto& c : s)
    {
        result *= 26;
        result += c  - 'A' + 1;
    }
    return result;
}
// Driver function
int main()
{
    cout << titleToNumber("CDA") << endl;
    return 0;
}

Output:

2133

Time Complexity = O(n) where n is length of input string.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/find-excel-column-number-column-title/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar