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')=65
12 
13             dict[i] = chr(j)
14             j += 1
15         while n / 26 > 0:
16             m = n%26
17             n = n/26
18             if m == 0:
19                 n = n - 1
20                 str += 'Z'
21                 
22             else:
23                 
24                 str += dict[m]
25         if n != 0:
26             m = n%26
27             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]

 

 
posted @ 2016-09-09 09:45  zdmlcmepl  阅读(123)  评论(0编辑  收藏  举报