网址:https://leetcode.com/problems/excel-sheet-column-title/
Total Accepted: 53072
Total Submissions: 253587
Difficulty: Easy
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
Credits:
我的AC:
char* convertToTitle(int n) {
char* ans = (char*) calloc (10,sizeof(char));
char true_ans[10];
int i = 0, j;
while(n){
ans[i++] = (n - 1) % 26 + 'A';//如果写成n % 26 + 'A' - 1,那Z就会出错!需if(n%26)来判断,很麻烦。
n = (n - 1) / 26;//如果n/=26,当输入26时输出为ZA,出错。
}
for (j = 0; j < i ; j++){
true_ans[j] = ans[i - 1 - j];
}
true_ans[j] = '\0';
return true_ans;
}
分析:
这个题做的时候脑子总绕不过弯来,看了许多discuss。
总结起来要注意2点:
1. (n - 1) % 26 + 'A'; n = (n - 1) / 26; 这么写,就不用再分情况讨论(有可能分的情况都分不对!)
2.最后需要加个reverse才行!