Problem Description
Explanation:
To convert the Excel sheet column title to its corresponding column number, we can iterate through the characters in the title from right to left. At each step, we calculate the value of the current character and add it to the result by multiplying the previous result by 26. This is because there are 26 letters in the English alphabet. Finally, we return the accumulated result as the column number.
Algorithm:
- Initialize a variable
result
to 0. - Iterate through the characters in the column title from right to left.
- At each step, calculate the value of the current character by subtracting 'A' from it and adding 1.
- Update the
result
by multiplying it by 26 and adding the value of the current character. - Return the final
result
as the column number.
Time Complexity: O(n) where n is the length of the column title.
Space Complexity: O(1)
:
Solutions
class Solution {
public int titleToNumber(String columnTitle) {
int result = 0;
for (int i = 0; i < columnTitle.length(); i++) {
int value = columnTitle.charAt(i) - 'A' + 1;
result = result * 26 + value;
}
return result;
}
}
Related LeetCode Problems
Loading editor...