Find Excel column number from column title
Last Updated :
11 Jul, 2022
We have discussed Conversion from column number to Excel Column name. In this post, reverse is discussed.
Given a column title as appears in an Excel sheet, return its corresponding column number.
column column number
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Examples:
Input: A
Output: 1
A is the first column so the output is 1.
Input: AA
Output: 27
The columns are in order A, B, ..., Y, Z, AA ..
So, there are 26 columns after which AA comes.
Approach: The process is similar to binary to decimal conversion.
For example, to convert AB, the formula is 26 * 1 + 2.
As another example,
To convert CDA,
3*26*26 + 4*26 + 1
= 26(3*26 + 4) + 1
= 26(0*26 + 3*26 + 4) + 1
So it is very much similar to converting binary to decimal keeping the base as 26.
Take the input as string and the traverse the input string from the left to right and calculate the result as follows:
result = 26*result + s[i] - 'A' + 1
The result will be summation of
.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int titleToNumber(string s)
{
int result = 0;
for ( const auto & c : s)
{
result *= 26;
result += c - 'A' + 1;
}
return result;
}
int main()
{
cout << titleToNumber( "CDA" ) << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG
{
static int titleToNumber(String s)
{
int result = 0 ;
for ( int i = 0 ; i < s.length(); i++)
{
result *= 26 ;
result += s.charAt(i) - 'A' + 1 ;
}
return result;
}
public static void main (String[] args)
{
System.out.print(titleToNumber( "CDA" ));
}
}
|
Python3
def titleToNumber(s):
result = 0 ;
for B in range ( len (s)):
result * = 26 ;
result + = ord (s[B]) - ord ( 'A' ) + 1 ;
return result;
print (titleToNumber( "CDA" ));
|
C#
using System;
class GFG
{
public static int titleToNumber( string s)
{
int result = 0;
for ( int i = 0; i < s.Length; i++)
{
result *= 26;
result += s[i] - 'A' + 1;
}
return result;
}
public static void Main( string [] args)
{
Console.Write(titleToNumber( "CDA" ));
}
}
|
Javascript
<script>
function titleToNumber(s)
{
let result = 0;
for (let i = 0; i < s.length; i++)
{
result *= 26;
result += s[i].charCodeAt(0) - 'A' .charCodeAt(0) + 1;
}
return result;
}
document.write(titleToNumber( "CDA" ));
</script>
|
Complexity Analysis:
- Time Complexity: O(n), where n is length of input string.
- Space Complexity: O(1).
As no extra space is required.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...