leetcode 实现-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
        """
        #需要注意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’

171题是给字符串求数字,正好与上面的相反

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        ord(‘A’)为65 
        """
        res = 0
        ll = len(s)
        for i in range(ll):
            res = 26**(ll-1-i)*(ord(s[i])-64)+res
        return res
        
原文地址:https://www.cnblogs.com/xiaojinniu425/p/9308720.html