【算法与数据结构相关】【LeetCode】【168 Excel表列名称】【Python】

题目:给定一个正整数,返回它在 Excel 表中相对应的列名称。例如,

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

思路:整体上就是进制转换,但是在余数和字符匹配时有点绕,余数的范围是0-25,字符对应的范围是1-26

代码:

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        assert n > 0
        n = n-1
        result = []
        result_str = ''
        if n == 0:
            return 'A'
        while n > 0:
            temp = n%26
            n = (n//26)-1
            result.append(temp)
        if n>=0:
            result.append(n)
        result.reverse()
        for item in result:
            result_str += chr(ord('A')+item)
        return result_str

注意:Python中字符与ascII码的转换:

  1. ord()将字符转换为ascII码
  2. chr()将ascII转换为字符

猜你喜欢

转载自blog.csdn.net/gq930901/article/details/81838094
今日推荐