Skip to content

Latest commit

 

History

History
102 lines (79 loc) · 2.11 KB

168-excel-sheet-column-title.md

File metadata and controls

102 lines (79 loc) · 2.11 KB

168. Excel Sheet Column Title - Excel表列名称

给定一个正整数,返回它在 Excel 表中相对应的列名称。

例如,

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

示例 1:

输入: 1
输出: "A"

示例 2:

输入: 28
输出: "AB"

示例 3:

输入: 701
输出: "ZY"

题目标签:Math

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
java 0 ms 35.3 MB
class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        while (n > 0) {
            sb.append(s.charAt((n - 1) % 26));
            n = (n - 1) / 26;
        }
        return sb.reverse().toString();
    }
}
Language Runtime Memory
cpp 0 ms 852 KB
class Solution {
public:
    string convertToTitle(int n) {
        string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string res;
        /*
        A-Z  1-26
        AA 27 26+1  26*1+1
        AB 28 26+2  26*1+2
        AZ    26*1+26
        BA    26*2+1
        BB    26*2+2
        ZY    26*26+25
        ZZ    26*26+26
        AAA   26*26*1+26*1+1
        */
        while (n) {
            if (n % 26 == 0) {
                res = 'Z' + res;
                n = n / 26 - 1;
            } else {
                res = alphabet[n % 26 - 1] + res;
                n /= 26;
            }
        }
        return res;
    }
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();