Excel Sheet Column Number Explained
Problem Statement
Given a string s representing an Excel column title (e.g., "A", "AB", "ZY"), return its corresponding column number. This is the reverse of converting a number to a title, treating the title as a base-26 number where A=1, B=2, ..., Z=26. This problem tests your ability to parse strings and perform base conversion.
Example
Input: s = "AB"
Output: 28
Explanation: AB = 1*26^1 + 2*26^0 = 26 + 2 = 28.
Code
Java
Python
JavaScript
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (char c : s.toCharArray()) {
result *= 26;
result += (c - 'A' + 1);
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.titleToNumber("AB")); // 28
}
}
def title_to_number(s):
result = 0
for char in s:
result *= 26
result += ord(char) - ord('A') + 1
return result
# Example usage
print(title_to_number("AB")) # 28
function titleToNumber(s) {
let result = 0;
for (let char of s) {
result *= 26;
result += char.charCodeAt(0) - 'A'.charCodeAt(0) + 1;
}
return result;
}
// Example usage
console.log(titleToNumber("AB")); // 28
Explanation
- Treat the string as a base-26 number, where each letter represents a digit.
- For each character, multiply the current result by 26 (shift left in base-26).
- Add the value of the current letter (A=1, B=2, ..., Z=26).
- Continue until all characters are processed.
- Return the final number.
Note
The time complexity is O(n), where n is the length of the string. Ensure the input string contains only uppercase letters A-Z to avoid invalid inputs.
