1023 Have Fun with Numbers

Posted kkmjy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1023 Have Fun with Numbers相关的知识,希望对你有一定的参考价值。

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位),假设这个数是a1a2a3...ak,把这个数乘以2倍,看得到的结果是否仍然是a1a2a3...ak的一个排列
 
思路:

大整数与int型整数的乘法;简单哈希。

代码:
#include <cstdio>
#include <cstring>

struct bign{
    int digit[30];
    int len;
    bign(){
        memset(digit,0,sizeof(digit));
        len=0;
    }
};

bign change(char str[])
{
    bign c;
    c.len=strlen(str);
    int n=c.len;
    for(int i=0;i<n;i++){
        c.digit[i]=str[n-1-i]-0;
    }
    return c;
}

bign multiply(bign a,int b)
{
    bign c;
    int carry=0;
    for(int i=0;i<a.len;i++){
        int temp=a.digit[i]*b+carry;
        c.digit[c.len++]=temp%10;
        carry=temp/10;        
    }    
    while(carry>0){
        c.digit[c.len++]=carry%10;
        carry/=10;
    }
    return c;
}

void print(bign a)
{
    for(int i=a.len-1;i>=0;i--)
        printf("%d",a.digit[i]);
}

int main()
{
    char str[30];
    scanf("%s",str);
    int hashtable[10];
    memset(hashtable,0,sizeof(hashtable));
    int len=strlen(str);
    for(int i=0;i<len;i++)
        hashtable[str[i]-0]++;
    bign a=change(str);
    bign double_a=multiply(a,2);
    for(int i=0;i<double_a.len;i++)
        hashtable[double_a.digit[i]]--;
    bool flag=true;
    for(int i=0;i<10;i++){
        if(hashtable[i]!=0) {
            flag=false;
            break;
        }
    }
    if(flag==true) printf("Yes
");
    else printf("No
");
    
    print(double_a);
    return 0;
}

 

 

以上是关于1023 Have Fun with Numbers的主要内容,如果未能解决你的问题,请参考以下文章

1023 Have Fun with Numbers

1023 Have Fun with Numbers

PAT 1023 Have Fun with Numbers

PAT 甲级 1023 Have Fun with Numbers

1023 Have Fun with Numbers (20)

1023 Have Fun with Numbers (20)(20 point(s))