Given a column title as appears in an Excel sheet, return its corresponding column number.
The following are example column numbers for given column names.
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Examples:Â
Input: A
Output: 1
Explanation: A is the first column so the output is 1.Input: AA
Output: 27
Explanation: The columns are in order A, B, ..., Y, Z, AA .. So, there are 26 columns after which AA comes.
Base-26 to Decimal - O(n) Time and O(1) Space
The process is similar to binary to decimal conversion. Treat the Excel column title as a base-26 number, where A = 1, B = 2, ..., Z = 26. Â For example, to convert AB, the formula is 26 * 1 + 2.
To convert CDA,
3*26*26 + 4*26 + 1
= 26(3*26 + 4) + 1
= 26(0*26 + 3*26 + 4) + 1
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
// C++ program to return title to result
// of excel sheet.
#include <bits/stdc++.h>
using namespace std;
// Returns result when we pass title.
int excelColumnNumber(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 << excelColumnNumber("CDA") << endl;
return 0;
}
// Java program to return title
// to result of excel sheet.
import java.lang.*;
import java.util.*;
class GFG {
// Returns result when we pass title.
static int excelColumnNumber(String s)
{
// This process is similar to
// binary-to-decimal conversion
int result = 0;
for (int i = 0; i < s.length(); i++) {
result *= 26;
result += s.charAt(i) - 'A' + 1;
}
return result;
}
// Driver Code
public static void main(String[] args)
{
System.out.print(excelColumnNumber("CDA"));
}
}
# Python program to return title to result
# of excel sheet.
# Returns result when we pass title.
def excelColumnNumber(s):
# This process is similar to binary-to-
# decimal conversion
result = 0;
for B in range(len(s)):
result *= 26;
result += ord(s[B]) - ord('A') + 1;
return result;
# Driver function
print(excelColumnNumber("CDA"));
// C# program to return title
// to result of excel sheet.
using System;
class GFG
{
// Returns result when we pass title.
public static int excelColumnNumber(string s)
{
// This process is similar to
// binary-to-decimal conversion
int result = 0;
for (int i = 0; i < s.Length; i++)
{
result *= 26;
result += s[i] - 'A' + 1;
}
return result;
}
// Driver Code
public static void Main(string[] args)
{
Console.Write(excelColumnNumber("CDA"));
}
}
// Function to convert Excel column title to number
function excelColumnNumber(s) {
let result = 0;
for (let i = 0; i < s.length; i++) {
result = result * 26 + (s.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
}
return result;
}
// Driver Code
console.log(excelColumnNumber("CDA"));
Output
2133