给定一个正整数,返回它在excel表中出现的对应列名称

For example:

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

Example 1:

Input: 1
Output: \"A\"

Example 2:

Input: 28
Output: \"AB\"

Example 3:

Input: 701
Output: \"ZY\"

1:构建数字对应字母的字典,然后进行计算(注意:没有0对应的字母,有26对应的字母)

def convertTo (self, n):

\"\"\"

:type n: int

:rtype: str

\"\"\"

chaDic = {1:\'A\', 2:\'B\', 3:\'C\', 4:\'D\', 5:\'E\', 6:\'F\', 7:\'G\', 8:\'H\', 9:\'I\', 10:\'J\', 11:\'K\'

, 12:\'L\', 13:\'M\', 14:\'N\', 15:\'O\', 16:\'P\', 17:\'Q\', 18:\'R\', 19:\'S\', 20:\'T\', 21:\'U\'

, 22:\'V\', 23:\'W\', 24:\'X\', 25:\'Y\', 26:\'Z\'} #注意,没有0对应的字母

rStr = \"\"

while n!=0:

if n<=26: #存在26对应的字母

rStr = chaDic.get(n)+rStr

n = 0

else:

res = n%26

if res == 0: #因为没有0对应的字母,所以如果余数为0的话需要自动提出26

res = 26

n -= 26

rStr = chaDic.get(res)+rStr

n = n//26

return rStr

2:利用chr()和ord()方法(参考他人代码)

chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符

ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常

def convertTo (self, n):

\"\"\"

:type n: int

:rtype: str

\"\"\"

rStr = \"\"

while n!=0:

res = n%26

if res == 0:

res =26

n -= 26

rStr = chr(ord(\'A\')+res-1) + rStr

n = n//26

return rStr


​​​​

算法题来自:https://leetcode-cn.com/problems/excel-sheet-column- /de ion/

收藏 打印