Python approach using base 26


  • 0

    Using a base 26 (26 values between ord('Z') and ord('A') ) one could represent an input like so:

    ABA = ((26^2)*A) + ((26^1)*B) + ((26^0)*A) = (26*26*1) + (26*2) + 1 = 729

    hence, to calculate the corresponding excel column:

    class Solution:
        def convertToTitle(self, n):
            """
            :type n: int
            :rtype: str
            """
            res = ''
            base = ord('Z')-ord('A')+1
            
            while n > 0:
                curr = n % base
                
                if curr == 0: 
                    res += 'Z'
                    n = int(n/base)-1
                else:
                    res += chr(curr + ord('A') - 1)
                    n = int(n/base)
                
                
            return ''.join(reversed(res))
    

Log in to reply
 

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