在Excel中,列名的表示情勢(shì)為A,B,C…AA,AB…,給定1個(gè)正整數(shù),將其轉(zhuǎn)換為對(duì)應(yīng)的列名。
注意點(diǎn):
例子:
輸入: n = 1
輸出: ‘A’
輸入: n = 28
輸出: ‘AB’
比較簡單的1道題,相當(dāng)于進(jìn)制轉(zhuǎn)換,轉(zhuǎn)換的基數(shù)為26。注意1下高地位的問題,后轉(zhuǎn)換出來的字母應(yīng)當(dāng)放在前面,還有所有字母都是大寫。
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = []
base = ord('A')
while n:
n, r = divmod(n - 1, 26)
result.append(chr(base + r))
return ''.join(result[::-1])
if __name__ == "__main__":
assert Solution().convertToTitle(1) == 'A'
assert Solution().convertToTitle(28) == 'AB'
歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來取得相干源碼。