1. 程式人生 > >LeetCode演算法題168:Excel表列名稱解析

LeetCode演算法題168:Excel表列名稱解析

給定一個正整數,返回它在 Excel 表中相對應的列名稱。
例如,

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

示例1:

輸入: 1
輸出: "A"

示例2:

輸入: 28
輸出: "AB"

示例3:

輸入: 701
輸出: "ZY"

這個題就是個進位制轉換題,非常簡單,直接把十進位制轉成26進位制就行,只是這裡的數從1開始,所以算的時候要減一才能使用整除符號和取餘符號。程式很簡單,直接看程式:
C++原始碼:

class Solution {
public:
    string convertToTitle(int n) {
        string s="";
        while(n)
        {
            s = char('A' + (n-1) % 26) + s;
            n = (n-1) / 26;
        }
        return s;
    }
};

python3原始碼:

class Solution:
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
s = "" while n: s = chr(ord('A') + (n-1) % 26) + s n = (n-1) // 26 return s