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
【分析】
题意:给你一个只有1~9组成的数串,求该串×2后是不是还是有这些数量的数字组成。输出Yes或No,并输出二倍后的结果。
思路:Hash。用两个数组分别存运算之前和运算之后各个数字出现的次数。注意!最高位进位的情况!(会有两个测试点5分)。比如,9+9=18,注意首位的1 。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
char s[25];
int a[10],b[10];
int main()
{
while(~scanf("%s",s))
{
int flag=0,tag=1;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int len=strlen(s);
for(int i=0;i<len;i++)
a[s[i]-'0']++;
for(int i=1;i<=9;i++)//如果有数字没用到也是不符合条件的
if(!a[i])tag=0;
for(int i=len-1;i>=0;i--)
{
int x=2*(s[i]-'0');
if(flag)x++,flag=0;
if(x>9)flag=1;
s[i]=x%10+'0';
b[x%10]++;
}
for(int i=0;i<10;i++)
if(a[i]!=b[i])
{
tag=0;break;
}
if(!tag)cout<<"No\n";
else cout<<"Yes\n";
len=strlen(s);
if(flag)cout<<"1";//如果最高位有进位,因为是加法,所以最高就是加1,所以直接输出1就好了
for(int i=0;i<len;i++)cout<<s[i];
cout<<endl;
}
}