Leetcode 168:Excel表列名稱(超詳細的解法!!!)
阿新 • • 發佈:2019-01-09
給定一個正整數,返回它在 Excel 表中相對應的列名稱。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
輸入: 1
輸出: "A"
示例 2:
輸入: 28
輸出: "AB"
示例 3:
輸入: 701
輸出: "ZY"
解題思路
這個問題很簡單,沒什麼難點,就是將餘數不斷新增到字串的最前面。
class Solution:
def convertToTitle (self, n):
"""
:type n: int
:rtype: str
"""
res = ''
while n:
n -= 1
res += chr(ord('A') + n%26)
n //= 26
return res[::-1]
實現的實收採用了一個trick
,就是n -= 1
,如果不這樣寫的話,會寫大量的判斷語句。
一個精彩的解法
class Solution :
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
return "" if num == 0 else self.convertToTitle((num - 1) / 26) + chr((num - 1) % 26 + ord('A'))
reference:
我將該問題的其他語言版本新增到了我的GitHub Leetcode
如有問題,希望大家指出!!!