自測4. 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位的數,然後乘以2,如果之後得到的數的組成與之前一樣,順序不同,那麼就輸出“Yes”,否則就“No”咯。要聲明一下,這道題如果用長整形之類的話,那麼大數的乘法是會有誤差的,可以自己先試試,你會發現得到的數會讓你大吃一驚。所以我們需要以另外一種方式來解決,我將每一位作爲一個字符輸入,然後再轉化爲整形數,存到一個整形數組中,接着通過兩個存儲了乘2前後數組成的數組比較,來判斷是否相同,由此來輸出答案,當然這種方法需要你自己寫代碼來進行乘法運算。只是乘2,應該都會得。

code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    int cnt=0;    //計數器
    //輸入數字
    int num[20];
    int a[10]={0};
    int b[10]={0};  //用於比較的數組a,b,其中元素爲含有這個數的個數
    while(1)
    {
        scanf("%c",&c);
        if((int)c-48>=0 && (int)c-48<=9)
        {
            num[cnt] = (int)c-48;       //將數存到數組中
            a[num[cnt]]++;   //個數+1
            cnt++;
        }
        else
            break;
    }
    //對數進行*2處理
    int i;
    int flag =0; //進位
    for(i=cnt-1;i>=0;i--)   //從最低位開始
    {
        num[i] = num[i]*2+flag;     //*2後的數
        if(num[i]>9 && i!=0)
        {
            flag =1;    //進位爲1
            num[i] = num[i]%10; //只留個位
        }
        else
            flag =0;
        if(num[0]<=9)
            b[num[i]]++;      //個數+1
    }
    //判斷a,b數組是否相同
    int sign = 0;
    for(i=0;i<10;i++)
    {
        if(a[i]!=b[i])
        {
            sign = 1;
            break;
        }
    }
    //輸出
    if(sign == 0)
        printf("Yes\n");
    else
        printf("No\n");
    for(i=0;i<cnt;i++)
    {
        printf("%d",num[i]);
    }
    return 0;
}


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