Excel Sheet Column Number Problem
Description
LeetCode Problem 171.
Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Example 4:
Input: columnTitle = "FXSHRXW"
Output: 2147483647
Constraints:
- 1 <= columnTitle.length <= 7
- columnTitle consists only of uppercase English letters.
- columnTitle is in the range ["A", "FXSHRXW"].
Solution
Approach: Read the Title as a Base-26 Number
A column title is a number written in base 26, where the digits are the letters A = 1 through Z = 26. Read it from left to right exactly as you would read a decimal number, where each new digit shifts the earlier ones one place left (multiply by 10) and is then added:
- Start with
number = 0. - For each letter, compute its digit
letter - 'A' + 1and setnumber = number * 26 + digit.
For "ZY": after Z, number = 26; after Y, number = 26 * 26 + 25 = 701.
The one detail is the + 1: A is worth 1, not 0. With 0-based digits, "A" and "AA" would both come out as 0.
The largest allowed title, "FXSHRXW", equals 2147483647, so the result and every intermediate value fit in a 32-bit integer.
Complexity: O(n) time and O(1) space, where n is the length of columnTitle (at most 7).
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
number = 0
for letter in columnTitle:
digit = ord(letter) - ord("A") + 1 # A = 1, ..., Z = 26
number = number * 26 + digit # shift the earlier letters one place left
return number
Now write it from memory
Close the write-up and solve it yourself against the tests.