Python solution with explanation


  • 37
    Z

    Let's see the relationship between the Excel sheet column title and the number:

    A   1     AA    26+ 1     BA  2×26+ 1     ...     ZA  26×26+ 1     AAA  1×26²+1×26+ 1
    B   2     AB    26+ 2     BB  2×26+ 2     ...     ZB  26×26+ 2     AAB  1×26²+1×26+ 2
    .   .     ..    .....     ..  .......     ...     ..  ........     ...  .............   
    .   .     ..    .....     ..  .......     ...     ..  ........     ...  .............
    .   .     ..    .....     ..  .......     ...     ..  ........     ...  .............
    Z  26     AZ    26+26     BZ  2×26+26     ...     ZZ  26×26+26     AAZ  1×26²+1×26+26
    

    Now we can see that ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4

    But how to get the column title from the number? We can't simply use the n%26 method because:

    ZZZZ=Z×26³+Z×26²+Z×26¹+Z=26×26³+26×26²+26×26¹+26

    We can use (n-1)%26 instead, then we get a number range from 0 to 25.

    class Solution:
        # @return a string
        def convertToTitle(self, num):
            capitals = [chr(x) for x in range(ord('A'), ord('Z')+1)]
            result = []
            while num > 0:
                result.append(capitals[(num-1)%26])
                num = (num-1) // 26
            result.reverse()
            return ''.join(result)

  • 0
    J

    This explanation perfectly explain why we should use (num-1) but not (num), and I spent half hour to think about this problem. lol, I was using (num/26), and always get AZ but not AA from 27


  • 0
    L

    Thanks for your explanation.


  • 0

    @jimmydada in fact you can use (num/26) , but you must carefully deal with the case in which remainder is 0. You must subtract you mod by 1 in this case.
    Details see this answer: https://discuss.leetcode.com/topic/51763/44-ms-python-solution-with-clear-explanations


  • 0
    R

    @yanchao_hust this is also what I did.


  • 0
    L

    @zhiqiang2 No need to store the letters:

    def convertToTitle(num):
            result = []
            while num > 0:
                result.append(chr((num-1)%26+ord('A')))
                num = (num-1) // 26
            result.reverse()
            return ''.join(result)

  • 0
    S

    Good explanation. The code can be a bit more concise:

        def convertToTitle(self, n):
            res, caps = '', [chr(i + 65) for i in xrange(26)]
            while n:
                n, rem = divmod(n - 1, 26)
                res = caps[rem] + res
            return res
    

  • 0
    T

    Great!, thanks for your explanation.

    You could use string.ascii_uppercase to avoid generating the capitals.
    And reversed() to make it one line shorter.

    def convertToTitle(x):
        result = []
        while x > 0:
            result.append(string.ascii_uppercase[(x - 1) % 26])
            x = (x - 1) // 26
        return "".join(reversed(result))
    

  • 0
    W

    Similar but with some simplifications

    class Solution(object):
        def convertToTitle(self, n):
            """
            :type n: int
            :rtype: str
            """
            r,o='',ord('A')
            while n>0:
                r, n = chr((n-1)%26+o)+r, (n-1)//26
            return r
    

Log in to reply
 

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