题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=303
解题思路:
省赛的水题。写了一下,第一次把题意理解错了,然后第二次写,发现数字转字母不会。。YY了才知道最后一个是Z时,总是26×26的0次方,不是26的话我们直接res/=26就可以把余数去掉,不影响下一个元素,而这个我们res/=26之后,这个Z结尾的26并没有去掉影响,所以res/=26之后还多了一个26,减去1就可以了。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
char s[10010], ans[10010];
void cmp(char *str) //数字转字母
{
int res = 0, top = 0;
int len = strlen(str);
for(int i = 0; i < len; ++i)
res += (int)((str[i] - '0') * pow(10.0, len - 1 - i));
while(res)
{
if(res % 26 != 0)
{
ans[top++] = res % 26 + 'A' - 1;
res /= 26;
}
else
{
ans[top++] = 'Z';
res = res / 26 - 1; //-1
}
}
for(int i = top - 1; i >= 0; --i)
printf("%c", ans[i]);
printf("\n");
}
int fun(char *str) //字母转数字
{
int sum = 0;
int len = strlen(str);
for(int i = len - 1, j = 0; i >= 0; --i, ++j)
sum += (int)(str[i] - 'A' + 1) * pow(26.0, j);
return sum;
}
int main()
{
int ncase;
scanf("%d", &ncase);
while(ncase--)
{
scanf("%s", s);
if(s[0] >= '1' && s[0] <= '9')
cmp(s);
else
printf("%d\n", fun(s));
}
return 0;
}