Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1023. Have Fun with Numbers

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

解答

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
	char s[50]; scanf("%s", s);

	int n = strlen(s);
	vector<int> a(n), b(n), c(n);
	for (int i = 0; i < n; i++) a[i] = s[i] - '0';

	int carry = 0;
	for (int i = a.size()-1; i >= 0; i--)
	{
		b[i] = a[i] * 2 + carry;
		if (b[i] >= 10) b[i] -= 10, carry = 1;
		else carry = 0;
	}
	if (carry) b.insert(b.begin(), 1);

	c = b;

	sort(a.begin(), a.end());
	sort(b.begin(), b.end());
	printf("%s\n", a==b ? "Yes" : "No");
	for (int i = 0; i < c.size(); i++) printf("%d", c[i]);
	printf("\n");
	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论