[LeetCode] 168. Excel Sheet Column Title 求Excel表列名称

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

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

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

给一个正整数,返回Excel表中对应的列标题。

解法:由例子可以看出是按26个字母循环,相当于10进制和26进制转换,所以可以对26取整取余。每有一个26就加一个A,剩下的余数对应相应的字母。

Python:

class Solution(object):
    def convertToTitle(self, n):
        result, dvd = "", n
        
        while dvd:
            result += chr((dvd - 1) % 26 + ord('A'))
            dvd = (dvd - 1) / 26
        
        return result[::-1] 

C++:

class Solution {
public:
    string convertToTitle(int n) {
        string res;
        while (n) {
            res += --n % 26 + 'A';
            n /= 26;
        }
        return string(res.rbegin(), res.rend());
    }
};

 

类似题目:

[LeetCode] 171. Excel Sheet Column Number 求Excel表列序号

 

All LeetCode Questions List 题目汇总

posted @ 2018-03-20 03:59  轻风舞动  阅读(1036)  评论(0编辑  收藏  举报