描述
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
Example 4:
Input: columnNumber = 2147483647
Output: "FXSHRXW"
Note:
1 <= columnNumber <= 2^31 - 1
解析
根据题意,就是用 26 进制的大写字母表示数字,思路比较简单,和对十进制数通过取模和整除 10 的得到每个数字的过程类似,只不过将每个数字都换成了对应的字母,最后记得将字符串倒序返回,因为在拼接过程中是从后向前的。
解答
class Solution(object):
def convertToTitle(self, columnNumber):
"""
:type columnNumber: int
:rtype: str
"""
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
r = ''
while columnNumber > 0:
m = (columnNumber-1) % 26
r += chars[m]
columnNumber = (columnNumber-1) // 26
return r[::-1]
运行结果
Runtime: 20 ms, faster than 34.68% of Python online submissions for Excel Sheet Column Title.
Memory Usage: 13.1 MB, less than 100.00% of Python online submissions for Excel Sheet Column Title.
原题链接:https://leetcode.com/problems/excel-sheet-column-title/
您的支持是我最大的动力