PAT 1023 Have Fun with Numbers[大数乘法][一般]

1023 Have Fun with Numbers (20)(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 file 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之后的结果b的各位是否恰巧是原来的数组成的(不包含新的数)。

#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;

int hasN[10],hasM[10];
int main(){
    //用long long好吗?,使用long long在牛客网上通过率为56.25%。
    //需要模拟大数乘法。
    //直接用string好了,可以reverse.
    char ch[30];
    scanf("%s",&ch);
    int len=strlen(ch);
    for(int i=0;ch[i]!='\0';i++){
        hasN[ch[i]-'0']+=1;//计算所含每个数的个数。
    }
    //将字符数组反转。
    int cha;
    for(int i=0;i<len/2;i++){//
        cha=ch[i];
        ch[i]=ch[len-i-1];
        ch[len-i-1]=cha;
    }
    int jin=0,tp=0,i;
    for(i=0;ch[i]!='\0';i++){
        tp=(ch[i]-'0')*2+jin;
        if(tp<10) {
            ch[i]=tp+'0';
            jin=0;
        }
        else {
            ch[i]=(tp%10+'0');
            jin=1;
        }
    }
    if(jin==1){
        ch[i]='1';
        ch[i+1]='\0';
    }
    bool flag=true;
    for(int i=0;ch[i]!='\0';i++){
            hasM[ch[i]-'0']+=1;
    }

    for(int i=0;i<10;i++){
        if(hasN[i]!=hasM[i]){
            flag=false;break;
        }
    }
    if(flag)
            cout<<"Yes\n";
        else
            cout<<"No\n";
    //printf("%s",ch);
    //计算结果应该倒序输出
    len=strlen(ch);
    for(int i=len-1;i>=0;i--){
        printf("%c",ch[i]);
    }
    return 0;
}

 

//这是我的AC代码,在牛客网上提交了3次。

1.直接用long long通不过,因为有很大的数。

2.使用字符数组,发现最终结果是错误的,因为没有将其倒序输出。

3.提交一个也没通过,因为发现,模拟数乘,需要将初始的倒序。

总之就是:将初始倒序,相乘,结果倒序输出。

学习到了:

1.判断字符数组的长度,使用strlen,头文件是<string.h>,不包括'\0'。

2.使用scanf读入字符输出,结束处会自己带一个'\0'。 

posted @ 2018-08-07 17:22  lypbendlf  阅读(166)  评论(0编辑  收藏  举报