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 
 
class Solution {
public:
    string convertToTitle(int n) {
        char turn[26] = {'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y'};
        string result;
        int i = 0;
        while(n)
        {
            i = n % 26;
            result.push_back(turn[i]);
            n = n / 26;
            if(i == 0)
                n = n - 1;
            
        }
        return result.assign(result.rbegin(), result.rend());
    }
};
  • 先向10进制的靠;
  • 但是发现在Z->AA的越界过程中,A在个位以上代表的是26,而Z本身又是26;所以当每次i%26为0,且n>=26时,需要把n--
  • 本质上是因为A-Z从1开始,而0-9从0开始

 

class Solution {
public:
    string convertToTitle(int n) {
        string ret = "";
        while(n)
        {
            ret = (char)((n-1)%26+'A') + ret;
            n = (n-1)/26;
        }
        return ret;
    }
};
  • 本质上就是将一个10进制数转换为一个26进制的数
  • 注意:由于下标从1开始而不是从0开始,因此要减一操作。
posted @ 2015-10-29 09:36  dylqt  阅读(129)  评论(0编辑  收藏  举报