# 44 ms python solution with clear explanations

• let [βn βn-1 ... β1] be a n-char string, so the number it represents is βn * 26^(n-1) + βn-1 * 26^(n-1-1) + ... + β1 * 26^(1-1)

for example:
A B C = A * 26^2 + B * 26^1 + C * 26^0
= 1 * 26^2 + 2 * 26^1 + 3

Z Z Z = Z * 26^2 + Z * 26^1 + Z * 26^0
= 26 * 26^2 + 26 * 26^1 + 26

To convert the number into string, we can always get the "small part" which is less or equal than 26.
We can divide the number by 26 recursively, the tricky part here is that when the remainder is 0, it means that the "small part" is exactly 26, so you must subtract the current number by 1. Here is the code:

``````class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
resStr = ""
numMod = n # in  case that n is 0 or less
while True:
if numMod <= 0:
break
numMod, numRem = divmod(numMod, 26)
if numRem == 0:
numMod -= 1
resStr = "Z"+resStr
else:
resStr = chr(64+numRem)+resStr #ord(A) = 65

return resStr

``````

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