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 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

Coding:

#include <stdio.h>
#include <string.h>

#define N 21

int main()
{
    char original[N];
    int doubledNum[N], i, digitsCount[10];
    int carry=0, isSame=1;
    gets(original);
    
    for(i=0; i<strlen(original); i++){
        doubledNum[i] = 2*(original[i] - '0');
    }
    for(i=strlen(original)-1; i>=0; i--){
        if(i>0){
            doubledNum[i-1] += doubledNum[i] / 10;
            doubledNum[i] %= 10;
        }
        else{
            carry += doubledNum[i] / 10;
            doubledNum[i] %= 10;
        }
        
    }
    if(carry){
        isSame = 0;
    }
    else{
        for(i = 0; i < 10; i++){
            digitsCount[i] = 0;
        }
        for(i = 0; i < strlen(original); i++){
            digitsCount[original[i] - '0']++;
        }
        for(i = 0; i < strlen(original); i++){
            digitsCount[doubledNum[i]]--;
        }
        for(i = 0; i < 10; i++){
            if(digitsCount[i] != 0){
                isSame = 0;
                break;
            }
        }
    }
    if(isSame){
        printf("Yes\n");
    }
    else{
        printf("No\n");
    }
    if(carry){
        printf("%d", carry);
    }
    for(i=0; i < strlen(original); i++){
        printf("%d", doubledNum[i]);
    }
    return 0;
}
posted @ 2021-07-24 22:21  zonkidd  阅读(23)  评论(0编辑  收藏  举报