Leetcode:excel Sheet Column Title

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.