Excel Sheet Column Number
Convert an Excel column title to its corresponding integer column number.
Open on LeetCode ↗Intuition
This is the mirror image of converting the other direction, and the trap mirrors it too: the instinctive ord(c) - ord('A') gives A a value of 0, matching plain base-26 digit indexing - but in this scheme A must be worth 1, not 0. Skip that +1 and every column number comes out too small, silently, for every single input. The fix is to add 1 after taking the offset, so ord(c) - ord('A') + 1 gives each letter its true place value, then fold the letters left to right with result = result * 26 + value, which is standard positional-number accumulation once the per-digit values are correct.
Horner's method: result = result * 26 + digit, left to right. The inverse of the title conversion, and easier because going this direction needs no off-by-one correction — the digit value is simply ch - 'A' + 1.
Approach
Compute each letter's true value
For each character in the title, take its offset from 'A' using ord(c) - ord('A'), then add 1 so that A maps to 1 and Z maps to 26 - matching the 1-indexed scheme instead of treating A as a zero digit.
Accumulate left to right
Walk the string from the first character to the last, updating result = result * 26 + value at each step. This is the same left-to-right accumulation used for any positional number system, once each digit's value is correct.
Return the accumulated result
After processing every character, the accumulator holds the exact column number - no separate power-of-26 lookup is needed because multiplying by 26 at each step already shifts prior digits into the right place.
Solution & live demo
Common pitfalls
Using a zero-based digit value
value = ord(ch) - ord('A')value = ord(ch) - ord('A') + 1A is column 1, not column 0. Without the + 1 every column comes out short and "A" maps to 0, which isn't a valid column at all.
Computing powers explicitly
for i, ch in enumerate(reversed(columnTitle)):
result += value * (26 ** i)result = result * 26 + value
Correct but computes a growing power at each step and needs the string reversed. Horner's form is one multiply-add per character, left to right, with no exponentiation.
Processing right to left without reversing the accumulation
for ch in reversed(columnTitle):
result = result * 26 + valuefor ch in columnTitle:
Horner's method requires the most significant digit first. Feeding it backwards computes the value of the reversed title — "AB" becomes 28 instead of 27.
Edge cases
Single letter, value = 0 + 1 = 1, result = 0*26 + 1 = 1.
Single letter, value = 25 + 1 = 26, result = 26 - the boundary case that plain base-26 (without +1) would get wrong.
First letter gives result = 1, second letter gives result = 1*26 + 1 = 27, correctly distinct from 'Z' = 26.
The same left-to-right multiply-and-add loop scales to any length without special-casing, bounded only by input size.