Excel Sheet Column Title

来源:互联网 发布:linux lnmp 编辑:程序博客网 时间:2024/06/06 15:46

这也是一道通过率偏低的easy题,但逻辑蛮明显的没什么难点,更多地是数字规律转化的考查。自己写的时候竟然是从后往前取余的,所以最后还得翻转回来,其实可以从前往后的,也就不用多此一举了。

如下:

char* convertToTitle(int n) {    // if (n == 0)    //     return NULL;    char *result = (char *)malloc(sizeof(char));    int temp = 0;    int index = 0;    while (n > 0) {        temp = n % 26;        n /= 26;        if (temp == 0) {            temp = 26;            n -= 1;        }        if (index > strlen(result)) {            result = (char *)realloc(result, sizeof(char) * index);        }        result[index] = 'A' + temp - 1;        index++;    }    int low = 0, high = (int)strlen(result) - 1;    char t = NULL;    while (low <= high) {        t = result[low];        result[low] = result[high];        result[high] = t;        low++, high--;    }//    int power = 0;//    while (n > 26) {//        n /= 26;//        power++;//    }//    result = (char *)malloc(sizeof(char) * (power + 1));//    int temp = 0;//    for (int i = power; i >= 0; i--) {//        temp = n % 26;//        result[i] = 'Z' - temp;//        n /= 26;//    }    return result;}


0 0