PAT Advanced 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 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位的整数n,如果n和2n使用相同次数的0 ~ 9,则输出Yes;否则输出No。并输出2n

#include<iostream>
#include<cstring>
#include<string>
using namespace std;

int ha[10];
bool check()
{
    for(int i = 0 ; i < 10 ; i ++)
        if(ha[i])
            return false;
    return true;
}

int main()
{
    string a, b, res;
    cin >> a;
    // 将a的各个位的数量存储在哈希表中 且 利用高精度加法原理存储两倍至b中
    int t = 0;
    for(int i = a.size() - 1 ; i >= 0 ; i --)
    {
        ha[a[i] - '0'] ++;
        t += (a[i] - '0') * 2;
        b += t % 10 + '0';
        t /= 10;
    }
    if(t)   b += '1';
    // 哈希表减去b中的每个位  并反转存储至res(高精度加法存储为逆序)
    for(int i = b.size() - 1 ; i >= 0 ; i --)
    {
        ha[b[i] - '0'] --;
        res += b[i];
    }
    // 如果最终哈希表中所有位都为0  则两个数串a,b匹配
    if(check())    cout << "Yes" << endl;
    else    cout << "No" << endl;
    cout << res;
    
    return 0;
}
posted @ 2022-08-21 22:30  D_coding_blog  阅读(38)  评论(0)    收藏  举报