【LeetCode】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 

提示:

此题考查的是将十进制数转换为N进制数的方法。需要注意的是,当进行转化时,每一步中的整除与取模操作,都需要对输入n进行减1后进行。

取模的时候减一是为了计算出相对于'A'这一字符在ascii码中的偏移量。

整除的时候减一是为了正确地计算出进位情况(比如26进制,在n=26时不需要进位,n=27时才会进位)。

代码:

class Solution {
public:
    string convertToTitle(int n) {
        string result;
        while (n) {
            result = (char)('A' + (n - 1) % 26) + result;
            n = (n - 1) / 26;    
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/jdneo/p/4741621.html