题目描述
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
大致意思
输入一个不超过20位的正整数,如果该数乘以2之后所使用的数字(0-9)及其个数与翻倍之前一样则返回“Yes”,否则返回“No”。举个例子1234567899,其中1有1个,2有1个,以此类推8也有1个,而9有两个;当该数翻倍之后变成2469135798仍然含有1-9共该9个数,且每个数的个数一样,则返回Yes。
自己的思路
用字符串保存输入的数字,然后记录转化成整数数组,记录每一个数字(0-9)出现的次数,然后将数组乘以2放大,如果整数长度扩大,那么肯定不符合题意直接输出No。如果长度未变,那么依次删除出现的数字的次数,如果每个数字最终记录的次数都为0,那么则满足题意输出Yes,否则输出No。最后输出扩大二倍之后的数字。
小白一个,单纯记录个人解发,欢迎大牛指点!
#include <iostream>
#include <string.h>
using namespace std;
int main(){
/*char a[21];
gets(a);//gets()在pat里编译不过去
int length=strlen(a);*/
string a;//用字符输入的方式是因为该整数最大20位,unsigned longlong也存不下,防止溢出。
getline(cin,a);
int length=a.length();
int i,num[length+1];/*length+1是避免2倍之后总长度+1 。比如输入7结果变成14,长度变成2了*/
int digit[10]={0};/*记录对应下标值的个数;比如digit[0]存放0的个数,digitp[1]存放1的个数*/
for(i=0;i<length;i++){
num[i]=a[i]-'0';//转换成整数
digit[num[i]]++;//对应的数的数量+1
}
/*cout<<"0-9的个数分别为:";
for(i=0;i<10;i++)
cout<<digit[i];
cout<<endl;*/
int add=0,j;//add是用来记录乘法的进位
for(i=length-1;i>=0;i--){
j=num[i]*2;//每位数扩大
j+=add; //记录是否有进位
if(j>=10){
num[i]=j-10;
add=1;
}else{
num[i]=j;
add=0;
}
}
if(add==1){//此时长度加1,每个数的使用次数肯定不符合了,直接输出No
for(i=length;i>=1;i--)//往最高位添加值
num[i]=num[i-1];
num[0]=1;
length++;
cout<<"No"<<endl;
} else{
for(i=0;i<length;i++){
digit[num[i]]--;
}
for(i=0;i<10;i++)
if(digit[i]!=0){
cout<<"No"<<endl;
add=2;
break;
}
if(add!=2)cout<<"Yes"<<endl;
}
for(i=0;i<length;i++)
cout<<num[i];
return 0;
}