PAT 甲级 1023 Have Fun with Numbers(20 分) C++版

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

判断一个k位数的两倍是不是原来那个数各个位数的全排列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdio>
#include <cstring>

int main() {
char s[22];
scanf("%s", s);
int *pers = new int[10], temp = 0, *pree = new int[10];
for (int i = strlen(s) - 1; i >= 0; i--) {
pers[s[i] - '0']++;
temp += 2 * (s[i] - '0');
s[i] = temp % 10 + '0';
pree[s[i] - '0']++;
temp /= 10;
}
if (temp != 0) pree[temp + '0']++;
bool state = true;
for (int i = 1; i <= 9; i++) {
if (pers[i] != pree[i]) {
state = false;
}
}
printf("%s\n", state ? "Yes" : "No");

if (temp != 0) printf("%d", temp);
printf("%s", s);
delete[] pree;
delete[] pers;
return 0;
}