PAT 甲级 1023 Have Fun with Numbers (20 分)题解

一、原题及翻译
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.
请注意,数字123456789是9位数字,完全由1到9组成,没有重复。将其翻倍,我们就获得了246913578,它恰好是由1到9组成,只是排列不同的9位数字。如果再次将其翻倍,请检查结果! 给定数字与k位数字加倍,请你检查结果数是否仅由原始数字中的数字排列组成。
Input Specification:
输入格式:

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
每个输入包含一个测试用例。每个案例包含一个不超过20位的正整数。

Output Specification:
输出格式:

For each test case, first print in a line “Yes” if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or “No” if not. Then in the next line, print the doubled number.
对于每个测试用例,如果翻倍后数字组成和翻倍前一样,则打印"Yes",否则打印"No",然后在下一行中,打印翻倍后的数字。
Sample Input:
输入样例:

1234567899

Sample Output:
输出样例:

Yes
2469135798

二、个人解析
淦,一上来我还憨憨的用了个long long。
我的思路就是实现带进位的加减法,先用ss把输入的数字装起来,然后翻转(便于实现加法进位),然后用cnt记录是否进位。(因为仅仅是翻倍,所以做的就比较简陋,没有考虑9+0+1的情况)

三、代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
#include<string>
using namespace std;
int main()
{
	string ss;
	cin >> ss;
	vector<int> db;
	vector<int> bf;
	int cnt = 0;
	bool same = 1;
	reverse(ss.begin(), ss.end());//为了实现低位先加,然后进位的操作
	for (int i = 0; i < ss.size(); i++)
	{
		int x = ss[i] - '0';
		bf.push_back(x);
		x = x * 2;
		db.push_back(x % 10 + cnt);
		if (x >= 10)
			cnt = 1;
		else
			cnt = 0;
	}
	if (cnt == 1)//最后若有进位,则在db还要加1
		db.push_back(1);
	if (db.size() != bf.size())
		same = 0;
	reverse(db.begin(), db.end());//翻转后才是真正的翻倍之后的数字
	vector<int> aa = db;
	sort(db.begin(), db.end());//排序便于比对
	sort(bf.begin(), bf.end());
	for (int i = 0; i < bf.size(); i++)
	{
		if (db[i] != bf[i])
		{
			same = 0;
			break;
		}
	}
	if (same == 0)
		cout << "No" << endl;
	else
		cout << "Yes" << endl;
	for (int i = 0; i < aa.size(); i++)
		cout << aa[i];
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值