PAT 1023 Have Fun with Numbers (20 分)

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




解析

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iterator>
using namespace std;
struct bign {
	int dig[21];
	int len;
	bign() {
		fill(begin(dig), end(dig), 0);
		len = 0;
	}
};
bign change(char* str, int len) {
	bign a;
	a.len = len;
	for (int i = 0; i <len; i++) {
		a.dig[i] = str[len - i - 1]-'0';
	}
	return a;
}
bign do_double(const bign& a) {
	int carry=0;
	bign b;
	b.len = a.len;
	for (int i = 0; i < a.len; i++) {
		int temp = a.dig[i] * 2+carry;
		b.dig[i] = temp % 10;
		carry = temp / 10;
	}
	while (carry != 0) {
		b.dig[b.len++] = carry % 10;
		carry /= 10;
	}
	return b;
}
int main()
{
	char input[23];
	scanf("%s", input);
	bign num = change(input, strlen(input));
	int digit[10]{ 0 };
	for (int i = 0; i < num.len; i++)
		digit[num.dig[i]]++;
	bign double_num = do_double(num);
	for (int i = 0; i < double_num.len; i++) {
		int j = double_num.dig[i];
		digit[j]--;
	}
	int zero = count_if(begin(digit), end(digit), [](int a) {
													return a == 0; });
	if (zero == 10)
		printf("Yes\n");
	else
		printf("No\n");
	for (int i = 0; i < double_num.len; i++)
		printf("%d", double_num.dig[double_num.len-i-1]);
}

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/84704062