Wednesday, August 22, 2012

Excel column header generator


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char out[27]={'Z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y',0};
char ans[100]={0};
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int j=0;
while(n>0)
{
int c=n%strlen(out);
//Using the remainder as the index of the character array.
ans[j]=out[c];
if(c==0)
{
n--;
}
n/=strlen(out);
j++;
}
//Reversing the answer string.
for(int i=0;i<strlen(ans)/2;i++)
{
char t=ans[i];
ans[i]=ans[strlen(ans)-i-1];
ans[strlen(ans)-i-1]=t;
}
cout<<ans<<endl;
}
return 0;
}

Sample Input: The first line is the number of test cases.
7
1
25
26
27
51
52
676

Sample Output:
A
Y
Z
AA
AY
AZ
YZ

No comments:

Post a Comment