flexme
BAN USERYour algorithm is wrong. You can try n = 26. This problem is not the same as number base conversion .
If you find that the numbers in each group of length is:
26, 26 * 26, 26 * 26 * 26,...
You will find the solution.
#include <iostream>
#include <string>
using namespace std;
string getNum(int num) {
int curgroup = 26;
int tot = 26;
int index = num;
while (tot < num) {
index -= curgroup;
curgroup *= 26;
tot += curgroup;
}
string ans;
while (curgroup > 26) {
int sg = curgroup / 26;
int ind = index / sg;
if (index % sg) ind++;
ans.push_back('A' + ind - 1);
index -= (ind - 1) * sg;
curgroup = sg;
}
ans.push_back('A' + index - 1);
return ans;
}
int main() {
int n;
while (cin >> n) {
cout << getNum(n) << endl;
}
return 0;
}
Try 26. It's wrong.
- flexme August 26, 2012