Title: Given A positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
Problem-Solving ideas: 10-in-turn 26-input system several points of note:
1.如何将数字转换成字符:使用指令chr(字符的ASCII码编号)。如chr(65)=‘A‘。2.如何将字符转换成数字:使用指令ord(‘字符‘)。如ord(‘A‘)=65。3.根据以上两条,可以令转换后的26进制字符: Title=chr[num%26+ord(‘A‘)]将26进制数字转换成字符。但是不能用 num%26 的方式,试想num=26,26%26=0。而ord(‘Z‘)=90,所以需要对num减1,即:Titel=chr[(num-1)%26+ord(‘A‘)]
Code:
class Solution(object):def convertToTitle(self, n): """ :type n: int :rtype: str """ return(" " if n==0 else self.converToTitle((n-1)/26)+chr((n-1)%26+ord(‘A‘)) """ X if Y else Z的意思是:如果Y真返回X否则返回Z self.convertToTitle:递归自己,即每一次使用(n-1)/26作为新n,进行chr((n-1)%26+ord(‘A‘))的计算 """
Code Listing 2:
class Solution(object):def convertToTitle(self, n): """ :type n: int :rtype: str """ Title = "" while(n>0): n -=1 Title = chr(n%26+65)+Title n /=26
Leetcode:excel Sheet Column Title