Description
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 kk 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.
Example:
Sample Input:
1234567899
Sample Output:
Yes
2469135798
Solution
#include<iostream>
using namespace std;
#include<string.h>
int main() {
int a[10][2];
memset(a, 0, sizeof(a));
char str[25];//initial string
cin >> str;
int len = strlen(str);
//cout << len;
int ccin = 0;
char str2[25];//string after double operation
int count = 0;
for (int i = len - 1; i >= 0; i--)
{
int t = str[i] - '0';
a[t][0]++;
int tmp = 2 * (t) + ccin;
str2[count++] = (tmp%10) + '0';
ccin = tmp / 10;
a[tmp % 10][1]++;
}
if (ccin)
{
str2[count] = '1';
a[1][1]++;
}
int equal = 1;
for (int i = 0; i < 10; i++)
{
if (a[i][0] != a[i][1])
{
equal = 0;
}
}
if (equal)
cout << "Yes" << endl;
else
cout << "No" << endl;
for (int i = len-1+ccin; i >= 0; i--)
{
cout << str2[i];
}
cout << endl;
return 0;
}
Review
字符串操作,由于位数限制20位,所以整型是不可以的。
字符串要考虑到进位问题。
比较数字是否‘相等’,设置一个二维数组a[10][2]
,用于统计0-9各个数字出现的频数,再有一个for循环进行比较。
PTA-自测-4 Have Fun with Numbers