-
Notifications
You must be signed in to change notification settings - Fork 2
/
excel_sheet_column_number.cpp
85 lines (60 loc) · 1.37 KB
/
excel_sheet_column_number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
Given a positive integer N, print its corresponding column title as it would appear in an Excel sheet.
For N =1 we have column A, for 27 we have AA and so on.
Note: The alphabets are all in uppercase.
Input:
The first line contains an integer T, depicting total number of test cases. Then following T lines contains an integer N.
Output:
For each testcase, in a new line, print the string corrosponding to the column number.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 107
Example:
Input:
1
51
Output:
AY
*/
#include<bits/stdc++.h>
using namespace std;
string convertToTitle(int n) {
string s;
while(n>0){
int ch=n%26;
if(ch==0){
s+='Z';
n=n/26-1;
}
else {
s+=char(ch+'A'-1); // 65 -> A
n=n/26;
}
}
reverse(s.begin(), s.end());
return s;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
cout<<convertToTitle(n)<<endl;
}
return 0;
}
/* Reverse of above question
int titleToNumber(string s) {
int res=0, k=0;
int n=s.length();
for(int i=n-1;i>=0;i--){
int ch=(s[i]-'A')+1;
res+=ch*pow(26,k++);
}
return res;
}
*.