Looking for fast and easy python solution


  • 0
    C
    class Solution:
    # @param {integer} n
    # @return {string}
        def convertToTitle(self, n):
            result = ''
            if n > 26:
                result = self.convertToTitle((n - 1)/ 26)
            result += chr(65 + (n - 1) % 26)
            return result
    

    This is my solution. Run time is around 68ms.
    However, Medium is around 44ms.
    Anyone can provide a better approach?
    Thanks.


  • 0
    M

    they problem is recursion. it is very expensive in python. use iteration can easily make to the median


  • 0
    A
    class Solution(object):
        def convertToTitle(self, n):
            """
            :type n: int
            :rtype: str
            """
            s = ''
            base = ord('@')
            while n:
                c = n % 26
                t = chr(c + base) if c else 'Z'
                n = (n - 1) / 26
                s = t + s
            return s
    

    My solution with iteration, which can get the run time < 40ms. However, the benchmark varies in different sumbits with the same code. :)


  • 0
    D
    class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        id2name = dict(enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1))
        colname = []
        while n > 0:
            i = n % 26
            if i == 0: i = 26
            colname.append(id2name[i])
            n = (n-i) / 26
        return "".join(colname[::-1])

  • 0
    S
    def excel_name(n):
        name = ''
        while(n > 0):
    	    n-=1
    	    name = chr (65 + n % 26) + name
    	    n /= 26
    
        return name

Log in to reply
 

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