PAT (Advanced Level) Practice 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
此題求一個數的2倍是不是這個數的一種排列。
開個陣列記錄0-9的次數,然後對照2倍的數,看看是否完全相同即可。
程式碼如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
char s1[25],s2[25];
int num1[15],num2[15];
int wei=0;
int main()
{
scanf("%s",s1);
memset (num1,0,sizeof(num1));
memset (num2,0,sizeof(num2));
int len=strlen(s1);
int jinwei=0,flag=0;
for (int i=len-1,j=0;i>=0;i--,j++)
{
num1[s1[i]-'0']++;
int t=(s1[i]-'0')*2+jinwei;
jinwei=t/10;
s2[j]=t%10+'0';
num2[s2[j]-'0']++;
}
if(jinwei)
{
s2[len++]=jinwei+'0';
num2[s2[len-1]-'0']++;
}
for (int i=0;i<10;i++)
{
if(num1[i]!=num2[i])
{
flag=1;
break;
}
}
if(flag)
printf("No\n");
else
printf("Yes\n");
for (int i=len-1;i>=0;i--)
printf("%c",s2[i]);
printf("\n");
return 0;
}