LeetCode 168. Excel Sheet Column Title

Post by ailswan Aug. 11, 2024

168. Excel Sheet Column Title

Problem Statement

link: LeetCode.cn LeetCode 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:

Input: columnNumber = 1 Output: "A"

Input: columnNumber = 28 Output: "AB"

Input: columnNumber = 701 Output: "ZY"

Constraints: 1 <= columnNumber <= 231 - 1

Solution Approach

The algorithm iteratively calculates the corresponding character for each digit in the base-26 numeral system by adjusting the column number and appending the appropriate character to the result string, which is then reversed to obtain the final column title.

Algorithm

  1. Base-26 Conversion: The solution treats the column number as a base-26 numeral system where ‘A’ corresponds to 1, ‘B’ to 2, and so on, until ‘Z’, which corresponds to 26.
  2. Offset Calculation: In each iteration, the offset (columnNumber - 1) % 26 is used to determine the correct character by mapping it to the range ‘A’ to ‘Z’.
  3. Reverse Construction: The characters are appended in reverse order during the calculation, so the resulting string is reversed at the end to produce the correct column title.

Implement

    class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = ""
        while columnNumber > 0:
            offset = (columnNumber - 1) % 26
            res += chr(ord('A') + offset)
            columnNumber = (columnNumber - 1) // 26
        return res[::-1]