Given a string representing the column name in an Excel sheet, return the number corresponding to the Excel column name.

For example, the following image shows numbers corresponding to Excel columns:

 
Excel column number to name

 
To better understand the solution, let’s first consider a simple mathematical relation. A number can be broken down into the sum of its digits multiplied by basen, where n is the number of positions the digit is away from the one’s place. For example, a decimal number 125 (having a base 10) can be written as (1 × 10 × 10) + (2 × 10) + 5.

 
Excel maps column names using the base number 26. If we apply the same logic to it, the excel column "ALH" can be broken down into (1 × 26 × 26) + (12 × 26) + 8, since A=1, L=12, and H=8. Programmatically, it can be done iteratively using a loop.

A = 1
AL = A × 26 + 12 = 1 × 26 + 12 = 38
ALH = AL × 26 + 8 = 38 × 26 + 8 = 996

Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

996

Java


Download  Run Code

Output:

996

Python


Download  Run Code

Output:

996

 
Also See:

Convert a number into a corresponding excel column name