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

题目大意

一道有关大整数运算的题,判断输入的数乘以2结果是否只是其数字的重排。注意如果位数多了一位就不满足,不能直接判断1~9数字出现的次数是否一样了,因为可能多了一个0。

#include
#include
using namespace std;
int main() {
	string in; cin >> in;
	int times[10] = { 0 },an[25],len=0,carry=0;
	for (int i = in.size() - 1; i >= 0; i--) {
		int t = in[i] - '0';
		times[t]++; //每个数字出现的次数
		an[len++] = (t * 2+carry) % 10;
		carry = (t * 2 + carry) / 10; //进位
	}
	if (carry != 0) an[len++] = carry; //还有进位则增加一位
	for (int i = 0; i < len; i++) {
		times[an[i]]--;
	}
	int flag = 1;
	if (len > in.size()) flag = 0; //漏了的话有一个测试点会无法通过
	for (int i = 1; i <= 9; i++) {
		if (times[i] != 0) flag = 0;
	}
	printf("%s\n", flag ? "Yes" : "No");
	for (int i = len - 1; i >= 0; i--) {
		cout << an[i];
	}
	return 0;
}

你可能感兴趣的:(PAT)