Python iterative, super clean with explaination


  • 0

    BAC is 2×(26^2) + 1×26 + 2 because we have visited all: xx + Axx (26^2) and x (26) and AB (2)
    So first we find the last char: (num-1) % 26 to get the index
    Then we divide n by 26 to become BA (2*26 + 1)
    Then we get the last char and loop again

    code:

    class Solution(object):
        def convertToTitle(self, n):
            
            charList = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
            res = ''
            while n > 0:
                res += charList[(n-1) % 26]
                n = (n-1) / 26  # let 26 become Z not AZ
            return res[::-1]
    

Log in to reply
 

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