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

代碼(c++)

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

int main()
{
    char num[20];
    int num1[20], num2[20];
    int i, j, count=0;

    //cout<<"輸入"<<endl;
    cin>>num;
    //cout<<"輸出"<<endl;
    //每個數存於數組中
    for(i=0;num[i]!='\0';i++)
    {
        num1[i] = num[i]-'0';//因是字符輸入,所以要進行ascii碼值轉換
        num2[i] = num1[i]*2;
        count++;
    }
    for(j=count-1;j>0;j--)//num2進位
    {
        if(num2[j]>9)
        {
            num2[j]-=10;
            num2[j-1]+=1;
        }
    }

    //判別
    int flag1[10]={0,0,0,0,0,0,0,0,0};//記錄數組中數字個數
    int flag2[10]={0,0,0,0,0,0,0,0,0};
    int flag3=0;
    if(num1[0]>4)
        cout<<"No"<<endl;
    else
    {
        for(i=1;i<10;i++)
        {
            for(j=0;j<10;j++)
            {
                if(num1[j]==i)
                    flag1[i]++;
                if(num2[j]==i)
                    flag2[i]++;
            }
        }
        for(i=0;i<10;i++)
        {
            if(flag1[i]==flag2[i])
                flag3++;
            else
                break;
        }
        if(flag3==10)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }
    for(i=0;i<count;i++)
        cout<<num2[i];
    cout<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章