【LeetCode每天一题】Excel Sheet Column Title(Excel的表格数)
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
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"
思路
这道题其实就是变相的将数字字符串转化成数字,数字是10进制,而这个题目中是26进制,我们根据数字判断是什么字母。例如:
A 1 AA 26+ 1 BA 2×26+ 1 ... ZA 26×26+ 1 AAA 1×26²+1×26+ 1
B 2 AB 26+ 2 BB 2×26+ 2 ... ZB 26×26+ 2 AAB 1×26²+1×26+ 2
. . .. ..... .. ....... ... .. ........ ... .............
. . .. ..... .. ....... ... .. ........ ... .............
. . .. ..... .. ....... ... .. ........ ... .............
Z 26 AZ 26+26 BZ 2×26+26 ... ZZ 26×26+26 AAZ 1×26²+1×26+26
ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4
解决代码
1 class Solution(object): 2 def convertToTitle(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 tem_dict = {1:'A', 2:'B', 3:'C', 4:'D', 5:'E', 6:'F',7:'G',8:'H', 9:'I',10:'J', 11:'K',12:'L', 8 13:'M',14:'N',15:'O',16:'P',17:'Q',18:'R',19:'S',20:'T',21:'U',22:'V',23:'W',24:'X', 9 25:'Y',26:'Z' 10 } # 预定义辅助字典 11 res = [] # 辅助列表 12 while n > 0: # 循环条件 13 res.append(tem_dict[((n-1)%26)+1]) # 每次使用n对26取余得到最后一位的数字,再在字典查找相应的字母。 14 n =(n-1)// 26 # 除以26 15 res.reverse() 16 17 return ''.join(res)