【演算法與資料結構相關】【LeetCode】【168 Excel表列名稱】【Python】
阿新 • • 發佈:2019-01-10
題目:給定一個正整數,返回它在 Excel 表中相對應的列名稱。例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
思路:整體上就是進位制轉換,但是在餘數和字元匹配時有點繞,餘數的範圍是0-25,字元對應的範圍是1-26
程式碼:
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ assert n > 0 n = n-1 result = [] result_str = '' if n == 0: return 'A' while n > 0: temp = n%26 n = (n//26)-1 result.append(temp) if n>=0: result.append(n) result.reverse() for item in result: result_str += chr(ord('A')+item) return result_str
注意:Python中字元與ascII碼的轉換:
- ord()將字元轉換為ascII碼
- chr()將ascII轉換為字元