168_Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB

Solution: recursive

We can divide the number by 26 repeatedly to get the number on each decimal, an then convert to the corresponding letter.

def convertToTitle(n):
    """
    :type n: int
    :rtype: str
    """
    rule = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E', 5:'F', 6:'G', 7:'H', 8:'I',
          9:'J', 10:'K', 11:'L', 12:'M', 13:'N', 14:'O', 15:'P', 16:'Q',
          17:'R', 18:'S', 19:'T', 20:'U', 21:'V', 22:'W', 23:'X', 24:'Y', 25:'Z'}
    if 1<= n <= 26:
        return rule.get(n - 1)
    else:
        return convertToTitle((n-1)//26) + rule.get((n-1)%26)

Note:

rule is set from 0 to 25, correspondingly use compute output for n-1, to avoid 26 not assigned to Z

Solution: Iterative

def convertToTitle(n):
    """
    :type n: int
    :rtype: str
    """
    output = ""
    while n > 0:
        output = chr((n-1)%26 + ord("A")) + output
        n = (n-1) // 26
    return output

Last updated