【leetcode】Python实现-168.Excel表列名称

168.Excel表列名称

描述

给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C

26 -> Z
27 -> AA
28 -> AB

示例
输入: 1
输出: “A”

输入: 28
输出: “AB”

输入: 701
输出: “ZY”

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        d = {}
        r = []
        a = ''
        for i in range(1,27):
            d[i] = chr(64+i)
        if n <= 26:
            return d[n]
        if n % 26 == 0:
            n = n/26 - 1
            a ='Z'
        while n > 26:
            s = n % 26
            n = n // 26
            r.append(s)
        result = d[n]
        for i in r[::-1]:
            result+=d[i]
        return result + a

通过了leetcode,但是自己测试,发现代码并不对。输入值为x乘以26,其中x-1可以被26整除时,我的程序就没法运行。hhh万万没想到居然贡献了一个测试用例。
别人。将十进制转换为二十六进制,但是从1开始,所以需要减一个1。emmm…涉及到数学推导的我也理解很慢,需要请教一下别人加深理解。

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        #需要注意26时:26%26为0 也就是0为A 所以使用n-1  A的ASCII码为65
        result = ""
        while n != 0:
            result = chr((n-1)%26+65) + result
            n = (n-1)/26
        return result

总结一下:
字符与ASCII码的转换:
- 字符转ASCII码 ord(str),如ord(‘A’)为65
- ASCII码转字符 chr(int),如chr(65)为’A’

你可能感兴趣的:(leetcode)