Leetcode刷题记录——168. Excel表列名称

Leetcode刷题记录——168. Excel表列名称_第1张图片
这道题我就操他妈了
调了半天才调出来
以下为我的蠢逼做法
最后给出一个好一些的方法

class Solution:
    def convertToTitle(self, n: int) -> str:
        thisdict = {}
        startascii = 65
        for i in range(26):
            thisdict[i+1] = chr(i+startascii)#] = i
        if n<=26:#shanglist
            return thisdict[n]
        zhengchu = 0
        if n % 26 == 0:
            zhengchu = 1
            n -= 1
        stack = []
        #找m,使得26^(m+1) >= n > 26^(m) 
        suma = 1
        while n > 26**suma:
            suma += 1
        suma -= 1
        while suma > 0:# and n >= 26:
            beishu = n // (26**suma)
            print(beishu)
            stack.append(beishu)
            n -= stack[-1]*(26**(suma))
            suma -= 1
        stack.append((n%26) + zhengchu*1) 
        for i in range(len(stack)-1):
            if stack[i] == 0:
                stack[i-1] -= 1
                stack[i] = 26
        res = ''
        index = 0
        start = 0
        while stack[start] == 0:
            start += 1
        stack = stack[start:]
        while stack != []:
            thisvalue = stack.pop(-1)
            res = thisdict[thisvalue] + res
        return res


以下是https://leetcode-cn.com/problems/excel-sheet-column-title/solution/python3san-xing-di-gui-jie-fa-by-lizzabrook1970/的方法

class Solution:
    def convertToTitle(self, n: int) -> str:
        table = [*map(chr, range(65, 91))]
        if n <= 26: return table[n - 1]
        return self.convertToTitle((n - 1) // 26) + table[(n - 1) % 26]

你可能感兴趣的:(leetcode,python编程技巧)