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表列序号

 

相关文章:

  • 2022-01-26
  • 2021-10-06
  • 2022-01-21
  • 2021-07-11
  • 2021-11-16
  • 2022-12-23
  • 2021-11-07
  • 2021-11-30
猜你喜欢
  • 2022-01-31
  • 2021-12-20
  • 2022-12-23
  • 2021-09-08
  • 2022-12-23
  • 2021-08-19
相关资源
相似解决方案