Python solution (linear time, linear space) with explanation


  • 1
    # linear time, and linear space complexity
    def convertToTitle(self, num):
        result = ""
        while num > 0:
            if num % 26 == 0:
                result = "Z" + result
                num = int(num / 26) - 1
            else:
                result = chr((num % 26) + 64) + result
                num = int(num / 26)
        return result
    

    Explanation:
    The majority of any cases you can come up with do fine by just dividing 26, and using the remainder to map it to a letter, but some cases can't be solved that way. For those cases you need to subtract 1 from num.

    Normal cases:
    53: BA
    53%26 = 1 (A) 53/26 = 2
    2%26 = 2 (B) 2/26 = 0

    27: AA
    27%26 = 1 (A) 27/27 = 1
    1%26 = 1 (A) 1/27 = 0

    Edge cases:
    26: Z
    26%26 = 0 26/26 = 0


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.