给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
思路:
十进制转二十六进制。
比较特殊的地方在于没有从0开始,一般十进制是0~9, 二进制是0~1,这个二十六进制是1~26.
所以需要处理一下:
每次循环先把n - 1,这样可以变成0~25的范围。
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ""
while(n):
n-=1
n, tmp = divmod(n, 26)
res = chr(ord("A") + tmp) + res
return res
下面的写于2019年7月18日18:55:57
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ""
while n:
n -= 1
char = chr(ord('A') + n % 26)
n /= 26
res += char
return res[::-1]