返回

[Leetcode]168. Excel Sheet Column Title(C++)

题目描述

题目链接:168. Excel Sheet Column Title

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 …

例子

例子 1

Input: 1 Output: “A”

例子 2

Input: 28 Output: “AB”

例子 3

Input: 701 Output: “ZY”

解题思路

这道题目可以看成是十进制到 26 进制的转换,但是注意一点这里的转换中 “A” 应该对应十进制中的 0, “Z” 对应十进制中的 25;所以我们每做一位转换之前将 n - 1 即可。代码如下所示:

#include <string>
#include <algorithm>

class Solution {
public:
    std::string convertToTitle(int n) {

        std::string result = "";
        while (n > 0) {
            n--;
            result += 'A' + (n % 26);
            n /= 26;
        }
        std::reverse(result.begin(), result.end());

        return result;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 168.ExcelSheetColumnTitle.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy