NYOJ-303 序号互换【模拟】

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值