Excel Sheet Column Number
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, ..., Z → 26, AA → 27, AB → 28, ..., ZY → 701.
Example 1
Input: columnTitle = "A"
Output: 1
Output: 1
Example 2
Input: columnTitle = "AB"
Output: 28
Explanation: A=1, B=2. AB = 1*26 + 2 = 28.
Output: 28
Explanation: A=1, B=2. AB = 1*26 + 2 = 28.
Example 3
Input: columnTitle = "ZY"
Output: 701
Output: 701
Solution Approach
This is essentially a base-26 to decimal conversion. Process characters left to right, accumulating the result by multiplying by 26 at each step and adding the value of the current character (A=1, B=2, ..., Z=26).
- Initialize
result = 0. - For each character
c:result = result * 26 + (c - 'A' + 1). - Return
result.
Java
class Solution {
public int titleToNumber(String columnTitle) {
int result = 0;
for (char c : columnTitle.toCharArray()) {
result = result * 26 + (c - 'A' + 1);
}
return result;
}
}
Complexity Analysis:
Time complexity: O(n) where n is the length of the column title string.
Space complexity: O(1). Only a result variable is used.