/************
** 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
**
***********/
Note:
1、首先观察,其实这是个26进制的计数方式,它是从1开始计数,而不是0. (27 - 1 = 26, 类似于 10 -0 = 10)
2、存储顺序跟输出方式相反,字符数组需要反转;
void invertChar(char *pChar) // 字符数组反转
{
char tmp;
int num = strlen(pChar) / sizeof(char);
char *pLeft, *pRight;
pLeft = pChar;
pRight = pChar + num - 1;
while(pLeft < pRight)
{
tmp = *pLeft;
*pLeft++ = *pRight;
*pRight-- = tmp;
}
}
char* convertToTitle(int n) // 计数方式
{
int i = 0;
static char excelSh[10];
while (n)
{
excelSh[i++] = 'A' + (n - 1) % 26;
n = (n - 1) / 26;
}
excelSh[i] = '\0';
invertChar(excelSh);
return excelSh;
}
/************
** Excel Sheet Column Number
**
** Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
1 -> A
2 -> B
3 -> C
…
26 -> Z
27 -> AA
28 -> AB
**
***********/
Note:
1、跟上一题反过来,这是将数字转化为对应的字符序号,理解题目按26进制数排序。
int titleToNumber(char *s)
{
int i = 0;
int toNumber = 0;
int nums = strlen(s) / sizeof(char);
for (; i < nums; i++) // 方法1
{
toNumber *= 26;
toNumber += s[i] - 'A' + 1;
}
return toNumber;
}