7-49 Have Fun with Numbers(20 分)

来源:互联网 发布:甲骨文云计算大会 编辑:程序博客网 时间:2024/06/05 22:38

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:

Yes2469135798
题目分析:此问题意在让我们判断给出一个数后,组成这个数的数字与这数乘二以后的组成数字是否完全相同。

由于题目的限制是不超过20位的数字,若采用整形也可能会造成越界问题。所以我们可以采用字符数组来存储大数并模拟大数的乘2运算。由于只是乘2运算,进位不是那么复杂,可以只在存储数组前空出一位方便进位即可。

代码:

#include <stdio.h>#include <string.h>int main (){    char start[21];    char end[21];    gets(start);//输入数    int t,i,j,m=0,s;    t=strlen(start);//存入数的长度即位数    int flag1=1;    if((start[0]-'0')*2>=10)//第一位数字大于5要进位,字符运算    {        end[0]='1';//乘2进位只可能为1        flag1=0;//位数改变则表明一定不同    }    for(i=t-1; i>=0; i--)//从末尾开始做乘法    {        if((start[i]-'0')*2>=10)//有进位        {            s=(start[i]-48)*2%10+m;            end[i+1]='0'+s;            m=1;//进位存储        }        else//无进位        {            s=(start[i]-48)*2+m;            end[i+1]='0'+s;            m=0;        }    }    int flag=1;    for(i=1; i<=t; i++)//在end数组中遍历,若存在两数相等,则在start数组中将此数变为a        for(j=0; j<t; j++)        {            if(end[i]==start[j])            {                start[j]='a';                break;            }        }    for(i=0; i<t; i++)//若start数组中不全为a,则证明有不同的数产生    {        if(start[i]!='a')        {            flag=0;            break;        }    }    if(flag==1)        printf("Yes\n");    else printf("No\n");    if(flag1==0)    {        for(i=0; i<=t; i++)//进位后输出从第一位开始        {            printf("%c",end[i]);        }    }    else    {        for(i=1; i<=t; i++)//无进位从第二位开始        {            printf("%c",end[i]);        }    }    return 0;}





原创粉丝点击