码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 168. Excel Sheet Column Title

时间:2016-09-09 10:16:20      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 

 

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]

 

 

leetcode 168. Excel Sheet Column Title

标签:

原文地址:http://www.cnblogs.com/lovely7/p/5855396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!