171. Excel Sheet Column Number
On LeetCode ->Problem¶
Convert an Excel column label to its 1-based column index.
A -> 1Z -> 26AA -> 27
Example:
Key trick¶
Treat the string like a base-26 number, but with digits A..Z mapped to 1..26 instead of 0..25.
Trap¶
The main mistake is using normal base-26 logic with A = 0, which gives wrong results for labels like A and AA.
Why is it interesting?¶
It tests whether you can recognize a custom positional numeral system and convert it cleanly in linear time.
Python solution¶
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
total = 0
# Standard left-to-right base-26 accumulation.
for ch in columnTitle:
total = total * 26 + (ord(ch) - ord("A") + 1)
return total
Comment on my solution¶
Your solution is correct.
- It computes the value from right to left using powers of 26.
- It has time complexity \(O(n)\) and space complexity \(O(1)\).
- A slightly more idiomatic version is to accumulate left to right, which avoids repeated exponentiation.
## Solution
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
total = 0
n = len(columnTitle)
for i in range(n):
ch = columnTitle[n - 1 - i]
digit = ord(ch) - ord("A") + 1
total += digit * (26**i)
return total
Solution().titleToNumber("A") # 1
Solution().titleToNumber("B") # 2
Solution().titleToNumber("AB") # 28
Solution().titleToNumber("ZY") # 701