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.

Input Specification:

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.

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.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

Code:

#include<bits/stdc++.h> 
using namespace std;

int main(){
	char num[22];
	scanf("%s",num); 
	//这里参考了柳神代码,使用char数组模拟大数
	
	set<int> s1;
	set<int> s2;
	for(int i=0;i<strlen(num);i++)
		s1.insert(num[i]-'0');
	
	char res[22];
	//flag当作进位
	int index=0,flag=0;
	for(int i=strlen(num)-1;i>=0;i--){
		int tmp=2*(num[i]-'0')+flag;
		if(tmp<10){
			res[index]=tmp+'0';
			flag=0;
		}
		else{
			res[index]=tmp%10+'0';
			flag=tmp/10;
		}
		index++;
	}
	if(flag!=0){
		s1.insert(flag);
		res[index]=flag+'0';
		index++;
	}
	
	for(int i=index-1;i>=0;i--)
		s2.insert(res[i]-'0');

	if(s1==s2) cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
	for(int i=index-1;i>=0;i--)
		cout<<res[i];
	
	return 0;
}

记录

  • char数组模拟大数(一开始用string出错了…)
  • scanf char数组不用加&
  • char数组长度用strlen
  • 注意进位时先乘2再加flag(即1)
  • 最后一个flag需要判断是否为1,如果是1也需要加到s2中!
  • permutation – n.置换; 排列(方式); 组合(方式)
  • duplication – n.(不必要的)重复;
上一篇:[day1-permutation]Inverse Problem


下一篇:[ICPC2020南京K] K Co-prime Permutation - 构造