Excel Sheet Column Title

Question

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB

Tags

  • Mathematics

Thought

The algorithm is straightforward and the implementation is below.

Notice: Remember to minus the number with 1 during the calculation, because the number is not started from 0.

Code

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

results matching ""

    No results matching ""