1023 Have Fun with Numbers (20)(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
题解1:
先把数据用string类型读入。
每计算一位数,记录原来数据的该位数个数和新数据的该位数个数,使用count数组计数。
判断两个数据的位数是否相等。如果不相等,直接输出“No”,同时输出最高位。
如果位数相等,判断每个数字的个数是否相等。如果不相等,输出“No”,否则输出“Yes”。
输出新数据的其他位数。
源代码1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num;
int res[20] = { 0 };
int i, j;
int temp, digit,len;
int count[2][10] = { 0 };
cin >> num;
len = num.size();
digit = 0;
j = 0;
for (i = len-1; i>=0; i--)
{
count[0][num[i] - '0']++;
temp = (num[i] - '0') * 2 + digit;
digit = temp / 10;
temp = temp % 10;
res[j++] = temp;
count[1][temp]++;
}
if (digit)
{
cout << "No" << endl;
cout << digit;
}
else
{
for (i = 0; i < 10; i++)
{
if (count[0][i] != count[1][i])
break;
}
if (i < 10)
cout << "No" << endl;
else
cout << "Yes" << endl;
}
for (i = j - 1; i >= 0; i--)
cout << res[i];
return 0;
}
题解2:
重复上述操作。唯一不同的是,不是单独计数两个数据的每个数字的个数,而是用新数据的个数减去旧数据的个数。最后判断count的每位数是否为0。如果为0,则说明两个数据的每个数字的个数相等。
源代码2:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num;
int res[20] = { 0 };
int i, j;
int temp, digit,len;
int count[10] = { 0 };
cin >> num;
len = num.size();
digit = 0;
j = 0;
for (i = len-1; i>=0; i--)
{
count[num[i] - '0']++;
temp = (num[i] - '0') * 2 + digit;
digit = temp / 10;
temp = temp % 10;
res[j++] = temp;
count[temp]--;
}
if (digit)
{
cout << "No" << endl;
cout << digit;
}
else
{
for (i = 0; i < 10; i++)
{
if (count[i] != 0)
break;
}
if (i < 10)
cout << "No" << endl;
else
cout << "Yes" << endl;
}
for (i = j - 1; i >= 0; i--)
cout << res[i];
return 0;
}