Solution 1: 从1开始的26进制
class Solution(object):
def convertToTitle(self, columnNumber):
"""
:type columnNumber: int
:rtype: str
"""
columnNumber = columnNumber - 1
columnName = []
while columnNumber//26 != 0:
columnName.append(chr(columnNumber%26 + 65))
columnNumber = (columnNumber - columnNumber%26)/26 - 1
columnName.append(chr(columnNumber%26 + 65))
return ''.join(columnName[::-1])
说明:一般性的进制转换题目无须进行额外操作,是因为我们是在「每一位数值范围在[0,x)」的前提下进行。但本题需要我们将从1开始,因此在执行「进制转换」操作前,我们需要先对 columnNumber 执行减一操作,从而实现整体偏移。
Solution 2: 另一种写法
class Solution(object):
def convertToTitle(self, columnNumber):
"""
:type columnNumber: int
:rtype: str
"""
## Solution 1
char_dict = {(i-64): chr(i) for i in range(65, 90)}
char_dict[0] = 'Z'
# print(char_dict)
num = columnNumber
columnName = []
while num//26 != 0:
# print('...')
# print(num//26)
n = num%26
# print(n)
columnName.append(char_dict[n])
if n==0:
n = 26
num = (num - n)/26
# print(num, columnName)
n = num%26
if n!=0:
columnName.append(char_dict[num%26])
return ''.join(columnName[::-1])