Excel Sheet Column Title Problem
Description
LeetCode Problem 168.
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
Example 4:
Input: columnNumber = 2147483647
Output: "FXSHRXW"
Constraints:
- 1 <= columnNumber <= 2^31 - 1
Solution
Approach: Base 26 With Digits 1 to 26
Column titles look like numbers written in base 26 with the letters as digits, but there is no zero digit: the digits run from A = 1 to Z = 26. Plain base-26 conversion therefore breaks on multiples of 26. For 26 it would compute remainder 0 and carry 1, which has no letter.
The fix is to subtract 1 before taking each digit. That maps the digits 1..26 onto 0..25, so n % 26 picks the letter directly and n / 26 is the correct carry:
- While
n > 0:n -= 1- the next letter (from the right) is
'A' + n % 26 n /= 26
- The letters come out last-first, so reverse them.
For 701: 700 % 26 = 24 gives Y, and 700 / 26 = 26. Then 25 % 26 = 25 gives Z, and 25 / 26 = 0. Reversed, the title is "ZY".
For 26: 25 % 26 = 25 gives Z and 25 / 26 = 0, so the answer is "Z". Without the subtraction, the remainder 0 would have no letter.
Complexity: O(log n) time and O(log n) space for the result, where n is columnNumber (the title has at most 7 letters).
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
letters = []
n = columnNumber
while n > 0:
n -= 1 # shift to 0-based so that A..Z become remainders 0..25
letters.append(chr(ord("A") + n % 26))
n //= 26
letters.reverse() # the last letter was produced first
return "".join(letters)
Now write it from memory
Close the write-up and solve it yourself against the tests.