自測-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)後的數字仍然是原數字組合而成,現在就是要讓你從控制檯輸入一個數字,然後你需要判斷它是否滿足上述條件,滿足:輸出Yes+加倍後的數字,不滿足:輸出No+加倍後的數字

解題思路:
對於這種數值特別大,大的連long long 型都存不下的時候,你就不能按照常規方法去求解這道題,應該使用字符數組,將其存儲在字符數組裏,然後使用的時候再強制轉換成整形,這裏一共需要三個數組,一個字符數組,四個整型數組,兩個整型數組分別存放原數字,和加倍後的數字,加倍方法:和計算加法一樣,*2>10的話就使上一位 +1。另外兩個整型數組用來判斷加倍前後數字組合方式是否一樣。一樣的話就直接輸出即可。
代碼:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char l[21];//因爲最大數值超出long long int的範圍,所以採用字符串輸入;
    int a[21],b[22];//用來記錄轉換的值;
    int n=0,i,j;//標記數的長度;
    scanf("%s",l);
    for(i=0; l[i]!='\0'; i++)
    {
        if(l[i]!='\0')
        {
            a[i]=l[i]-'0';
            b[i]=a[i]*2;
            n++; //記錄輸入數據的位數;
        }

    }
    for(i=n-1; i>0; i--) //進位;
    {
        for(j=i; j>0; j--)
        {
            if(b[j]>9)
            {
                b[j]-=10;
                b[j-1]+=1;
            }
        }
    }
    //判別;
    int a1[10]= {0,0,0,0,0,0,0,0,0,0};
    int a2[10]= {0,0,0,0,0,0,0,0,0,0};
    if(b[0]>9)
        printf("No\n");
    else
    {
        for(i=1; i<10; i++)
        {
            for(j=0; j<10; j++)
            {
                 if(a[j]==i)
                    a1[i]++;
                 if(b[j]==i)
                    a2[i]++;
            }
        }
        for(i=1;i<10;i++)
        {
            if(a1[i]==a2[i]);
            else
                break;
        }
        if(i==10)
            printf("Yes\n");
        else
            printf("No\n");
    }
    for(i=0;i<n;i++)
        printf("%d",b[i]);

}

運行結果:
運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章