题目:
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
题目大意:
统计double后的数列中各个位上的数的个数是否与原数列一致,如案例中‘9’出现了2次,double后仍出现2次。
输出格式如上。
思路:
1、20位整数需要通过数列存储,同时需要长度进行打印控制。如此便构造结构体bign 。要判断是否一致,则构造(int)hashtable。
2、输入时用字符串录入,需要change函数进行变换,返回bign 型变量,同时将字符串的地址位存储到bign型变量中的数组d的高地址位,同时令相应的hashtable[x]++。退出循环后,要将高位的0除去,且对应的hashtable--(为进行相关运算的方便,统一从低地址位开始循环控制)
3、用dbl(函数)进行double乘法运算,循环控制:每次运算中原数列的每位乘2后加上进位的个位赋值给新数列,且令其十位赋值给进位变量;同时对相应位上的hashtable[x] --。因一位数乘进位只能为一位,退出循环时要加上最后的进位。(n位数乘k位数必小于(n+1+k)位且大于(n-1+k)位,由夹逼定理得必为n+k位)
4、用judge(函数)进行判断。若长度不一必输出“No”。否则循环控制:若新数列的某位的hashtable[x]不为0,则需要打印“No”。退出循环 则意味着都为0,需要打印“Yes”。
#include<cstdio>
#include<cstring>
int hashtable[10]={0};
struct bign{
int len,d[21];
bign(){//进行初始化
len=0;
memset(d,0,sizeof(d));
}
};
bign change(char a[]){
bign ans;
ans.len=strlen(a);
for(int i=0;i<ans.len;++i){
ans.d[i]=a[ans.len-1-i]-'0';
hashtable[ans.d[i]]++;//对应位置加一
}
while(ans.len>1&&ans.d[ans.len-1]==0){
hashtable[ans.d[ans.len-1]]--;
ans.len--;//除去最高位的0且减一
}
return ans;
}
bign dbl(bign a){
bign ans;
int num=0,carry=0;
bool printed=0;
for(int i=0;i<a.len;++i){
ans.d[num]=(a.d[i]*2+carry)%10;
carry=(a.d[i]*2+carry)/10;
hashtable[ans.d[num]]--;
num++;
}
if(carry!=0) ans.d[num++]=carry;
ans.len=num;
return ans;
}
bool judge(bign a,bign b){
if(a.len!=b.len) return false;
for(int i=0;i<a.len;++i){
if(hashtable[i])
return false;
}
return true;
}
int main(){
char s[21];
scanf("%s",s);
bign a=change(s);
bign ans=dbl(a);
if(judge(a,ans)) printf("Yes\n");
else printf("No\n");
for(int i=ans.len-1;i>=0;--i)
printf("%d",ans.d[i]);
printf("\n");
return 0;
}
注:有部分代码参考《算法笔记》