Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Constraints:
1 <= columnTitle.length <= 7
columnTitle consists only of uppercase English letters.
columnTitle is in the range ["A", "FXSHRXW"].
My Solution
We can solve this problem by iterating through the columnTitle string and at each character we subtract the ASCII value of the character from the ASCII value of ‘A’ and add that to the column number. We have to remember to also add 1 to that since the columnTitles are offset by 1. At every character we also have to multiply by 26.
Time complexity would be O(n), where n is the length of the columnTitle string since we iterate once through it. Space complexity would be O(1) since we only require constant extra space.
class Solution {
public int titleToNumber(String columnTitle) {
int columnNumber = 0;
for (char c : columnTitle.toCharArray()) {
columnNumber *= 26;
columnNumber += (int)(c - 'A' + 1);
}
return columnNumber;
}
}