首页 > 代码库 > leetcode 168. Excel Sheet Column Title

leetcode 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 

问题:

1要特殊考虑到Z的显示

2.chr(65)=A  ord(‘A‘)=65

3.dict={1:‘A‘,3:‘B‘}

dict[1]=A

4.反转字符串s,s[::-1]

 1 class Solution(object): 2     def convertToTitle(self, n): 3         """ 4         :type n: int 5         :rtype: str 6         """ 7         dict = {} 8         j = 65 9         str = ‘‘10         for i in range(1,27):11             #chr(65)=A  ord(‘A‘)=6512 13             dict[i] = chr(j)14             j += 115         while n / 26 > 0:16             m = n%2617             n = n/2618             if m == 0:19                 n = n - 120                 str += Z21                 22             else:23                 24                 str += dict[m]25         if n != 0:26             m = n%2627             str += dict[m] 28         29         return str[::-1]30         31 32 33 s = Solution()34 print s.convertToTitle(52)

 

 

 

用到知识点

对于str类型,python并没有reverse函数。然而,通过反向步进切片,我们可以高效地反转一串字符串。

s = ‘abcde‘ s[::-1]

 

 

leetcode 168. Excel Sheet Column Title