Python Solution beats 80%


  • 0
    R
    class Solution(object):
        def convertToTitle(self, n):
            """
            :type n: int
            :rtype: str
            """
            converter = [chr(x) for x in range(ord('A'), ord('Z')+1)]
            if n == 0 or n is None:
                return None
            ret_str = ""
            while n > 26:
                to_append = n % 26
                n = n / 26
                if to_append == 0:
                    n -= 1
                ret_str = converter[to_append - 1] + ret_str
            if n > 0:
                to_append = n % 26
                ret_str = converter[to_append - 1] + ret_str
            return ret_str
    

    The way I initially thought about it was like converting an int to binary, but instead, this is base 26. There was a side case I tripped up on which was when you have a value that goes evenly into 26, you need to take 1 off of your number after you divide it. This is because you would be double counting.


Log in to reply
 

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