1. 程式人生 > 其它 >PAT 甲級 1023 Have Fun with Numbers

PAT 甲級 1023 Have Fun with Numbers

技術標籤:c++

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

題意:將old number乘以2之後獲得的新number中的數字組成及其個數和old number一致,但是不同的排列。

思路:
1.將old number和new number都儲存在字串中,方便呼叫length()函式進行位數比較;
2.採用兩個int陣列來儲存old number和new number中每個數字出現的次數,陣列下標0到9代表出現的數字;
3.審題清楚,輸出格式規範,Yes和No輸出之後還要輸出一次new number(我一開始就是沒注意到這個細節所以有三個測試點過不了);
4.不要忘記處理最後的進位,比如最高位是9,那麼最後的進位還有一個1;

#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
int res1[11],res2[11];
int main()
{
	int flag=1;
	string str1,str2;
	cin >> str1;
	for (int i = 0; i < str1.length(); i++)
		res1[str1[i] - '0']++;          //old number
	int j = 0,add=0;
	string c;
	for (int i = str1.length() - 1; i >= 0; i--) {        //double it
		c=(2 * (str1[i] - '0') % 10+add)+'0';
		str2.insert(j,c);                                 //new number
		add = 2 * (str1[i] - '0') / 10;
		j++;
	}
	if (add) {                  //不要忘記對最後的進位做出處理
		c = add + '0';
		str2.insert(j, c);
	}
	for (int i = 0; i < str2.length(); i++)
		res2[str2[i] - '0']++;
	if (str1.length() == str2.length()) {     //比較兩個number的位數是否一致
		for (int i = 0; i < 10; i++) {        //比較兩個number中出現的數字的個數是否一致
			if (res1[i] != res2[i]) flag = -1;
		}
		if (flag == 1) printf("Yes\n");
		else printf("No\n");
	}
	else printf("No\n");
    for (int i = str2.length() - 1; i >= 0; i--)
		printf("%c", str2[i]);
	return 0;
}