This problem is the reverse of LeetCode 168.
Instead of converting a number to a column title, here you are given a column title (like used in Excel) and must convert it into the corresponding integer.
Examples:
Input: "A" → Output: 1 Input: "Z" → Output: 26 Input: "AA" → Output: 27 Input: "AB" → Output: 28 Input: "ZY" → Output: 701
Problem Understanding
Excel column titles behave like a base-26 number system, but instead of digits 0–25, letters represent values 1–26:
A → 1 B → 2 ... Z → 26 AA → 27 AB → 28 ...
So the string must be interpreted like a positional numeral:
For "AB": A contributes 1 * 26¹ B contributes 2 * 26⁰
Logic Explained in Simple English
Think of the column title as a number written in a special alphabet-based system.
To convert it into a number:
- Start with result = 0
- Read characters from left to right
- For each character:
- Convert it to a number between 1 and 26
Example: ‘C’ → 3 - Multiply the current result by 26
- Add the character’s numeric value to result
- Convert it to a number between 1 and 26
- Continue until the end of the string
- Return result
Why this works:
- Each character acts like a digit position
- Earlier characters are more significant
- Multiplying by 26 shifts previous value left, like base conversion
This is identical to converting a base-26 number to decimal, with letters instead of digits.
Step-by-Step Approach
- Initialize result = 0
- Loop through each character in the string
- Convert character to numeric value:
value = character - 'A' + 1 - Update:
result = result * 26 + value - Return result
Java Implementation
class Solution {
public int titleToNumber(String columnTitle) {
int result = 0;
for (char c : columnTitle.toCharArray()) {
int value = c - 'A' + 1;
result = result * 26 + value;
}
return result;
}
}
Dry Run Example
Example Input: "AB"
Initial:
result = 0
Step 1: Character ‘A’
value = 1 result = 0 * 26 + 1 = 1
Step 2: Character ‘B’
value = 2 result = 1 * 26 + 2 = 28
Final Output:
28
Dry Run Example: "ZY"
Initial:
result = 0
Step 1: ‘Z’
value = 26 result = 0 * 26 + 26 = 26
Step 2: ‘Y’
value = 25 result = 26 * 26 + 25 = 676 + 25 = 701
Final Output:
701
Time and Space Complexity
Time Complexity
O(n)
(n = length of column title)
Space Complexity
O(1)
Common Mistakes and How to Avoid Them
Mistake 1: Treating ‘A’ as 0
In this problem:
A = 1, not 0
Mistake 2: Processing from right to left
Left-to-right is simpler due to multiplication accumulation.
Mistake 3: Using Math.pow
Unnecessary and slower — multiplication is enough.
Mistake 4: Overflow concerns
Not an issue within constraints, but use long if extending.
Mistake 5: Confusing with problem 168
168 converts number to title — this does the reverse.
