题目
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
思路
通过对整数不断除26即可完成。但是要注意一下,当整数为26的整倍数时,要做一点特殊的处理。
实现代码如下:
#define N 100
void swap(char *a,char *b){
int temp=*a;
*a=*b;
*b=temp;
}
char* convertToTitle(int n) {
if(n<1){
return NULL;
}
char *res=(char *)malloc(N*sizeof(char));
if(res==NULL){
exit(EXIT_FAILURE);
}
int index=0;
while(n){
int temp=n%26;
if(temp==0){//注意:要对26 的整倍数做一点特殊处理
res[index++]='Z';
n=(n/26)-1;
}
else{
res[index++]='A'+temp-1;
n=n/26;
}
}
//将res翻转就是最后的结果
int begin=0;
int end=index-1;
while(begin<end){
swap(res+begin,res+end);
begin++;
end--;
}
res[index]='\0';
return res;
}
java实现代码如下:
public String convertToTitle(int n) {
if(n<1){
return null;
}
char []alph="ZABCDEFGHIJKLMNOPQRSTUVWXY".toCharArray();
StringBuffer sb=new StringBuffer();
while(n!=0){
int temp=n%26;
sb.insert(0, alph[temp]);
if(temp==0){
n-=26;
}
n/=26;
}
return sb.toString();
}