题目
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
题目链接:https://leetcode-cn.com/problems/excel-sheet-column-title
解法一:新建一个字典dicts,键为顺序值,值为大写字母对n%26==0的情况做-1处理
class Solution:
def convertToTitle(self, n: int) -> str:
dicts = {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'}
res = ''
while n > 0:
if n%26==0:
res = dicts[26]+res
n = n//26-1
else:
res = dicts[n%26]+res
n = n//26
return res
解法二:新建一个数组arr存放26个大写字母,将"Z"放在arr[0]位置,即n%26对应的值。26的倍数26、52等分别对应A、AZ,对n%26==0的情况做-1处理。
class Solution:
def convertToTitle(self, n: int) -> str:
arr = ['Z','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']
res = ''
while n>0:
res = arr[n%26]+res
if n%26==0:
n = n//26-1
else:
n = n//26
return res