天天看點

leetcode excel表格列标題數字與字元串的轉換

1 數字轉換為字元:

    1 -> A

    2 -> B

    3 -> C

    ...

    26 -> Z

    27 -> AA

    28 -> AB 

int getindex(int l){
if(l==1)return 1;
else return (getindex(l-1)+pow(26.0,(l-1)));}//擷取字元數為l的第一個字元串對應的數值比如A->1,AA->27

char* convertToTitle(int n) {
   if(n<1)return NULL;
   int l=0;
   int old=n;
   while(n){
   n=(n-1)/26;
   l++;}
   char *p=(char *)malloc(sizeof(char)*(l+1));
   for(int i=0;i<l;i++)
	   p[i]='A';
   p[l]='\0';
   int sum=old-getindex(l);
   for(int i=0;i<l;i++){
	
   p[l-i-1]=sum%26+'A';
   sum=sum/26;}
   return p;
}
           

2 字元串轉數字

    A -> 1

    B -> 2

    C -> 3

    ...

    Z -> 26

    AA -> 27

    AB -> 28

int getindex(int l){
if(l==1)return 1;
else return (getindex(l-1)+pow(26.0,(l-1)));}
int titleToNumber(char* s) {
 int l=strlen(s);
 if(l==0)return 0;
 int sum=0;
 for(int i=0;i<l;i++){
 sum*=26;
 sum+=(s[i]-'A');}
 return sum+getindex(l);
}