LeetCode168Excel表列名称

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

例如,

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

示例 1:

输入: 1
输出: "A"

示例 2:

输入: 28
输出: "AB"

示例 3:

输入: 701
输出: "ZY"
char* convertToTitle(int n) {
    //减一除26取余,直接预先分配一个足够大的空间
    int x;
    char *s,a;
    int size = 10;
    s = (char *)malloc(size * sizeof(char));
    int i = 0;
    if(n <= 26) 
        {
        s[0] = n + 64;
        return s;
    }
    while(n){
        x = (n - 1) % 26;
        s[i++] = x + 65;
        n = (n - 1)/26;
    }
    int len = strlen(s);
    for(int i = 0; i < len/2; i++)
        {
        a = s[i];
        s[i] = s[len-1-i];
        s[len-1-i] = a;
    }
    return s;
}

猜你喜欢

转载自blog.csdn.net/a_learning_boy/article/details/84396184
今日推荐