168. Excel Sheet Column Title
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"
来自 <https://leetcode.com/problems/excel-sheet-column-title/description/>
思路1:这相当于一个26进制的转换问题,但特殊之处在于,它是从A开始到Z结束,按照题目规定A为1,Z为26,而不是一般情况下的从0到25。我们仍然可以先进行普通的26进制转换,之后再处理这一问题。
1 class Solution(object): 2 def convertToTitle(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 yushu = [] 8 while n > 0: 9 yushu.append(n % 26) 10 n = n // 26 11 for i in range(len(yushu)-1): 12 if yushu[i] <= 0: 13 yushu[i+1] = yushu[i + 1] - 1 14 yushu[i] = yushu[i] + 26 15 yushu=yushu[::-1] 16 if yushu[0] == 0: 17 del (yushu[0]) 18 s = '' 19 for i in yushu: 20 s += chr(i + 64) 21 return s
思路2:上面的解法在逻辑上有点模糊,其实对于每一次循环n应该等于n-1因为,这样就能将1到26转换为0到25
1 class Solution(object): 2 def convertToTitle(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 yushu=[] 8 while n>0: 9 yushu.append((n-1)%26+65) 10 n = (n-1)//26 11 yushu=yushu[::-1] 12 result='' 13 for i in yushu: 14 result+=chr(i) 15 return result
思路3:对于这种重复执行问题,可以用递归方法处理
1 class Solution(object): 2 def convertToTitle(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 if n == 0: 8 return "" 9 else: 10 return self.convertToTitle((n - 1) // 26)+chr((n - 1) % 26 + ord('A'))