Problem
Given a column title as it appears in an Excel sheet (A, B, …, Z, AA, AB, …), return its corresponding column number.
Example
Input: "A"
Output: 1
Input: "AB"
Output: 28
Solution
Treat as base-26 number. Each letter contributes (letter – A + 1) * 26^position.
def title_to_number(s):
result = 0
for ch in s:
result = result * 26 + (ord(ch) - ord('A') + 1)
return result
function titleToNumber(s) {
let result = 0;
for (const ch of s) {
result = result * 26 + (ch.charCodeAt(0) - 'A'.charCodeAt(0) + 1);
}
return result;
}
int titleToNumber(string s) {
int result = 0;
for (char ch : s) {
result = result * 26 + (ch - 'A' + 1);
}
return result;
}
public int titleToNumber(String s) {
int result = 0;
for (char ch : s.toCharArray()) {
result = result * 26 + (ch - 'A' + 1);
}
return result;
}
Complexity
- Time: O(n)
- Space: O(1)
Explanation
Like reading a base-26 number left to right. Multiply running total by 26 and add the next digit value.
Comments
Join the discussion. Got a question, found an issue, or want to share your experience?