Write a function to convert an Excel sheet column title to its corresponding column number. The input will be a string consisting of uppercase English letters. The output should be an integer representing the corresponding column number.
Example:
Input: "A", Output: 1
Input: "B", Output: 2
Input: "Z", Output: 26
Input: "AA", Output: 27
Input: "AB", Output: 28
To solve this problem, we need to first understand how Excel sheet column titles are represented. In Excel, the first column is represented as "A", and each subsequent column is represented by adding a letter to the end of the previous column. Once we get to "Z", the next column becomes "AA", and so on.
Given a column title, we need to convert it to its corresponding column number. To do this, we can start by initializing a result variable to 0. We will then iterate through each character in the input string, and for each character, we will multiply the current result by 26 and add the value of the current character. We need to subtract the character code for "A" from the character code of the current character, and add 1 to get the value of the current character.
Here's the implementation:
function getColumnNumber(columnTitle) {
let result = 0;
for (let i = 0; i < columnTitle.length; i++) {
const charCode = columnTitle.charCodeAt(i) - 64; // subtract the character code for "A"
result = result * 26 + charCode; // multiply the current result by 26 and add the value of the current character
}
return result;
}
Big O Complexity Analysis: The time complexity of the function is O(n) because we iterate through each character in the input string exactly once. The for loop that iterates through the input string runs n times, where n is the length of the input string.
The space complexity of the function is O(1) because we only use a constant amount of extra space to store the result variable. We don't create any new arrays or objects, and the amount of extra space used does not depend on the size of the input string.