PAT1023 Have Fun with Numbers

1023. 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 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位超过了int的32字节所以不能直接乘,需要按字符获得后进行计算;

//
//  main.cpp
//  1023
//
//  Created by apple on 14-2-13.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#include <iostream>
#include <string>
using namespace std;
int array_num[21];
int mutiply_num[21];
int flag[10];
int flag1[10];

int main(int argc, const char * argv[])
{

    int i;
    int len;
    int tmp;
    int success_flag;
    string str;
    cin>>str;
    len = str.size();
    for (i =0; i < 10; i++) {
        flag[i] = 0;
        flag1[i] = 0;
    }

    for (i = 0; i <21; i++) {
        mutiply_num[i] = 0;
    }

    for (i= len-1; i >=0; i--) {
        if (str[len-1-i]>='0' && str[len-1-i] <='9') {
            array_num[i] = str[len-1-i] - '0';
            flag[array_num[i]]++;
         }
    }
    
    
    for (i=len-1;i>=0 ; i--) {
        tmp = array_num[i] *2;
        if(tmp <10){
            mutiply_num[i] = tmp;
        }
        else
        {
            mutiply_num[i] = tmp%10;
            mutiply_num[i+1] += 1;
        }
        
    }
    
    if (mutiply_num[len]!=0) {
        success_flag = 0;
        cout<<"No"<<endl;
        for (i =len; i>=0; i--) {
            cout<<mutiply_num[i];
        }
        cout<<endl;
        return 0;
    }
    else
    {
        for(i = len -1; i>=0; i--)
        {
            flag1[mutiply_num[i]]++;
        }
        for(i= 0; i<10;i++)
        {
            if (flag[i] != flag1[i]) {
                success_flag = 0;
                break;
            }
            
            
        }
        if (i == 10) {
            success_flag = 1;
        }
    }
    
    if (!success_flag) {
        cout<<"No"<<endl;
    }
    else if(success_flag == 1){
        cout<<"Yes"<<endl;
    }
    
    for (i = len-1; i >=0; i--) {
        cout<<mutiply_num[i];
    }
    
    cout<<endl;
    
    return 0;
    
}

 

posted @ 2014-02-13 23:21  likelight  阅读(540)  评论(0编辑  收藏  举报