
Description
The problem is to convert a given Excel column title (as it appears in an Excel sheet) into its corresponding column number. For example, the column title "A" corresponds to 1, "AB" to 28, and "ZY" to 701. The task is to simulate this conversion process and return the correct column number.
Intuition
Excel column titles are based on a base-26 numeral system, where each letter represents a digit, with 'A' corresponding to 1, 'B' to 2, and so on up to 'Z' for 26. The problem is essentially about converting a string from this custom base-26 system into a decimal number. The conversion is similar to how we convert a number from a numeral system like binary or hexadecimal to a decimal number.
Approach
- Initialization:
- Start with a variable
countinitialized to0. This will hold the final column number. - Iterate Through the Column Title:
- Traverse each character of the column title string.
- For each character, calculate its position in the alphabet (e.g.,
'A'corresponds to1,'B'to2, etc.) by subtracting the ASCII value of'A'and adding1. - Update thecountby multiplying the existing value by26(since it's base-26) and then adding the positional value of the current character. - Return the Result:
- After processing all characters, the
countvariable will contain the final column number.
Complexity
Time Complexity:
O(n), where n is the length of the column title. Each character in the string is processed once.
Space Complexity:
O(1) additional space is required, as the solution only uses a few extra variables for calculations.
Code
C++
class Solution {
public:
int titleToNumber(string columnTitle) {
int count = 0;
for (char c : columnTitle) {
int currentVal = c - 'A' + 1;
count = count * 26 + currentVal;
}
return count;
}
};Python
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
count = 0
for c in columnTitle:
currentVal = ord(c) - ord('A') + 1
count = count * 26 + currentVal
return countJava
class Solution {
public int titleToNumber(String columnTitle) {
int count = 0;
for (int i = 0; i < columnTitle.length(); i++) {
int currentVal = columnTitle.charAt(i) - 'A' + 1;
count = count * 26 + currentVal;
}
return count;
}
}JavaScript
var titleToNumber = function(columnTitle) {
let count = 0;
for(let i=0; i < columnTitle.length; i++){
let currentVal = columnTitle.charCodeAt(i) - "A".charCodeAt(0) +1;
count = count * 26 + currentVal
}
return count;
};