168 excel sheet column title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1
2
3
4
5
6
7
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

思路

归根到底,这道题就是一个进制转换的问题。只不过把传统的10->2 / 10->8 / 8->16 等等,变成了26进制的转化而已。

注意在python当中,ord()函数用来获取一个字符的ASCII码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ""
while (n > 0):
if (n % 26 != 0):
res = chr(n % 26 + ord("A") - 1) + res
n = n / 26
else:
res = "Z" + res
n = (n / 26) - 1
return res