7-49 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
思路:
- 由于该数字长度最大为20位,超过了int,long,long long型可表示的范围,因此只能用字符数组来保存它
类型 | 字节数 | 表示范围 |
---|---|---|
int | 4 | -2147483648~+2147483647 |
long int | 4 | -2147483648~+2147483647 |
long long int | 8 | -9223372036854775808~+9223372036854775807 |
获得字符数组的两种方法:
1、gets()函数:从输入缓冲区读入一行
2、scanf("%s",&string):读入一个字符串放入字符数组中
-
定义int类型的digit数组初始化为0,判断在加倍过程中是否产生新数,具体过程为:
(1)、依次对每一位数进行判断,每一次判断对digit数组中以当前数为下标的位置中的内容加一
(2)、对当前数加倍,得到当前位置加倍后的数,并且对digit数组中以当前加倍的数为下标的位置中的内容减一 -
在加倍过程中考虑进位问题和字符型与整型的转化问题
(1)、从数组中最后一位数进行判断,初始进位数carry为0,若加倍后的数加进位数大于10则改变进位数carry为该数除以10,该数模10得到当前位置的数
(2)、char型转化为int型:字符a-‘0’‘0’为char型字符,其ASCII码为48,若字符a是’1’,其ASCII码为49,则a-'0’结果为int型的1
-
遍历数组digit,若有不为0的位置,则输出“No”,否则为“Yes”
-
注意输出加倍数时若最高位有进位也要输出
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
char a[21]={0};
//gets(a);//gets()函数从标准输入流读入一整行,以"\n"结束
scanf("%s",&a);
int len=strlen(a);
int digit[10]={0};//统计数的个数
int carry=0;//判断是否进位
int flag=0;//判断是否没有产生新的数
/*for(int i=0;i<len;i++)
{
printf("%d",a[i]-'0');//字符型转int型
}*/
for(int i=len-1;i>=0;i--)
{
int t=a[i]-'0';//原数组当前位置的数,减'0'转化为整型
digit[t]++;//记录该数
t=2*t+carry;//加倍后该位置的数
a[i]=t%10+'0';//进位后
digit[a[i]-'0']--;
carry=t/10;//向前进位
}
for(int i=0;i<10;i++)
{
if(digit[i]!=0)
{
flag=1;
break;
}
}
if(flag==1)
printf("No\n");
else
printf("Yes\n");
if(carry)//输出加倍后的数字
printf("%d",carry);
for(int i=0;i<len;i++){
printf("%d",a[i]-'0');
}
//printf("%s",a);
return 0;
}