LeetCode-168. 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”

算法

和传统的数字分成每一位的算法还是有区别的,传统的数字是0,1,2,…,9,然后是10,而不是11,而这个字母是A,B,C,…,Z,然后是AA,而不是BA,所以这个每次循环除以26以后还要再减1,即i=i/26-1才是这个算法的关键所在,我当时做的时候并没有发现这个特点,所以做的特别特别复杂,我做的太麻烦了就不往上贴了,下面贴一个用C语言做的看起来比较简单的代码。

代码

char* convertToTitle(int n) {
    if(n<1) return "";
    int len = 0;
    for(int i=n-1; i>=0; i=i/26-1) len++;
    char *Title = (char*)malloc(sizeof(char)*len);
    for(int i=n-1; i>=0; i=i/26-1) Title[--len] = i%26 + 'A';
    return Title;
}

猜你喜欢

转载自blog.csdn.net/weixin_41580638/article/details/88035200