LeetCode Excel Sheet Column Title

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"

本题要求把数字转换为Excel中的列的名称,规则就是题中给出的例子。 可以看到是26进制,比如1048,除以26余数为8,商为40,则最后一个字母就是’A’+8-1=’H’;然后用40继续循环,40除以26余数为14,商为1,则倒数第二个字母为’A’+14-1=’N’,第一个字母为’A’。 需要注意能整除26的情况,比如26,余数为0,此时应该是字母’Z’,然后在n/=26的基础上,把n减1。完整代码如下:

class Solution {
public:
    string convertToTitle(int n)
    {
        string ans = "";
        while (n > 0) {
            int r = n % 26;
            char c = r – 1 + ‘A’;
            n /= 26;
            if (r == 0) {
                ans = ‘Z’ + ans;
                n–;
            }
            else {
                ans = c + ans;
            }
        }
        return ans;
    }
};

本代码提交AC,用时0MS。

1 thought on “LeetCode Excel Sheet Column Title

  1. Pingback: LeetCode Excel Sheet Column Number | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *