自测-4 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

题目解读:
大概意思即:给你一个数,观察其2倍是否为原先各位数字的新的排列组合。(此处隐含一个条件,即新的数字与原有数字位数相同)

解题思路:
由于输入数字可达20位,int型不再合适,并且要统计各位数字,比较是否为排列组合,我们选择char数组,直接将各位数字分开

答案:

#include<stdio.h>
#include<string.h>
#define maxsize 25//设置数组长度并留出余量
int test(int part1[],int part2[]);//声明比较函数
void divide(char num[],int part[]);//声明统计函数
int multi(char num[]);//声明乘法函数
int main()
{
    char num[maxsize];
    int part1[10]={0},part2[10]={0};//两个数组分别用来统计新旧两个数0-9十个数字的出现次数
    scanf("%s",num);
    divide(num,part1);//对原数据分割统计
    if(!multi(num))//计算新数据,并比较位数(比较过程在乘法函数内)
    {
        return 0;//新旧数字位数不同,不可能为排列组合,强制结束程序
    }
    divide(num,part2);分割统计新数据
    if(test(part1,part2))//以下为输出部分
    {
        printf("Yes\n");
    }
    else
    {
        printf("No\n");
    }
    printf("%s",num);
    return 0;
}
int test(int part1[],int part2[])//比较函数
{
    int i;
    for(i=0;i<10;i++)
    {
        if(part1[i]!=part2[i])
        {
            return 0;//0-9任何一个数字出现次数不同则不是
        }
    }
    return 1;
}
void divide(char num[],int part[])
{
    int max=strlen(num);
    int i,ind;
    for(i=0;i<10;i++)
    {
        part[i]=0;
    }//初始化统计数组
    for(i=0;i<max;i++)
    {
        ind=num[i]-'0';//计算在统计数组中的下标
        part[ind]++;
    }
}
int multi(char num[])
{
    int carry=0,i,max,cont;//初始设进位为0
    max=strlen(num);
    for(i=max-1;i>=0;i--)
    {
        cont=num[i]-'0';//由char到int
        cont=2*cont+carry;
        carry=cont/10;//计算进位
        cont=cont%10;//计算该位
        num[i]=cont+'0';//由int到char
    }
    if(carry!=0)//最终进位不为零,说明两数位数不匹配,判错
    {
        printf("No\n");//按题目要求进行输出
        printf("%d",carry);
        printf("%s",num);
        return 0;//返回错误标记,在主程序中结束进程
    }
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值