168. Excel Sheet Column Title
感觉自己有点愚蠢做的这一题,其实就是把它变成0-25之间就清楚了
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
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
stack = []
while n:
stack.append(alpha[(n-1) % 26])
n = (n-1) / 26
stack.reverse()
return ''.join(stack)