2014-05-01 01:50
原题:
Microsoft Excel numbers cells as ... and after that AA, AB.... AAA, AAB...ZZZ and so on.
Given a number, convert it to that format and vice versa.
题目:微软的Office Excel对于每行每列的命名方式是1, 2, 3, ..., 26, AA, AB, ..., ZZ, AAA, ..., ZZZ。请写个函数完成这种“数字”和自然数的互相转换。
解法:数清楚每个长度“数字”的个数,然后分段转换即可。
代码:
// http://www.careercup.com/question?id=6139456847347712
#include <cstdio>
#include <iostream>
#include <string>
using namespace std; string intToString(int n)
{
string s = ""; if (n <= ) {
while (n > ) {
s.push_back(n % + '');
n /= ;
}
reverse(s.begin(), s.end());
return s;
} int exp;
int len; exp = ;
len = ;
while (n > exp) {
n -= exp;
++len;
exp *= ;
} --n;
for (int i = ; i < len; ++i) {
s.push_back(n % + 'A');
n /= ;
}
reverse(s.begin(), s.end()); return s;
} int stringToInt(const string &s)
{
int n = ;
int len = (int)s.length(); if (s[] >= '' && s[] <= '') {
sscanf(s.c_str(), "%d", &n);
return n;
} int exp = ; for (int i = ; i < len; ++i) {
n += exp;
exp *= ;
}
exp = ;
for (int i = ; i < len; ++i) {
exp = exp * + (s[i] - 'A');
}
n += exp;
++n; return n;
} int main()
{
int n;
string s; while (scanf("%d", &n) == && n > ) {
s = intToString(n);
n = stringToInt(s);
cout << n << ' ' << s << endl;
} return ;
}