letecode [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 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

题目大意

   根据给定规则:1对应A,2对应B,...,26对应Z,27对应AA,...。给定正整数n,求得对应的字符串。

理  解:

   类似于重写26进制数。

  取余n计算n的当前末尾数值,取模n更新n为去掉末尾后的数,根据对应关系,末尾数值对应字母,放到字符串中。

  若n等于0,则已转换完成;或v==0且n==1表明当前n为26,则转换完成。

  注:转换完成后,需要把字符串逆置。reverse(str.begin(),str.end())。

代 码 C++:

class Solution {
public:
    string convertToTitle(int n) {
        char res;
        string str;
        int v;
        while(1){
            v = n % 26;
            n = n / 26;
            if(v==0){
                res = 'Z';
                n--;
            }    
            else
                res = v + 64;
            str += res;
            if(n==0)
                break;
        }
        reverse(str.begin(),str.end());
        return str;
    }
};

运行结果:

   执行用时 :4 ms, 在所有C++提交中击败了91.13%的用户

  内存消耗 :8.1 MB, 在所有C++提交中击败了40.40%的用户
posted @ 2019-06-11 14:51  lpomeloz  阅读(140)  评论(0编辑  收藏  举报