题目
https://www.patest.cn/contests/pat-a-practise/1023
题意:输入一串不超过20位的数字,将该数字串乘以两倍后,判断新数串是否为原数串的一个排列。
解题思路
统计旧字符串中数字0-9的出现次数和新字符串中数字0-9的出现次数,若两者完全相同,则新数串是原数串的一个排列。
AC代码
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[25];
cin >> str;
int s[25], index = 0;
int old_cnt[10] = {0};
for (int i = strlen(str)-1; i >= 0; --i)
{
s[index++] = str[i]-'0'; //store digits inversely
old_cnt[str[i]-'0']++; //count each digit
}
//double
int res[25] = {0}, new_cnt[10] = {0}, tmp;
for (int i = 0; i < index; ++i)
{
tmp = s[i] << 1;
res[i] += tmp%10;
res[i+1] += tmp/10;
}
if (res[index] != 0)
new_cnt[res[index]]++;
for (int i = 0; i <= index; ++i)
{
if (i != index)
new_cnt[res[i]]++;
else if (res[index] != 0)
new_cnt[res[index]]++;
}
//check
bool flag = true;
for (int i = 0; i <= 9; ++i)
{
if (old_cnt[i] != new_cnt[i])
{
flag = false;
break;
}
}
if (flag) cout << "Yes" << endl;
else cout << "No" << endl;
for (int i = index; i>=0; --i)
{
if (i == index && res[index] == 0) //leading digit is zero
continue;
cout << res[i];
}
cout << endl;
return 0;
}