PAT甲級1023 Have Fun with Number

冷眼觀world發表於2020-11-04

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.

翻譯:請注意,數字123456789是一個9位數的數字,完全由1到9組成,沒有重複。給它加倍之後我們將得到246913578,它恰好是另一個9位數的數字,正好包含從1到9的數字,只是排列不同。如果我們再加倍看看結果!
現在,假設您要檢查是否有更多具有此屬性的數字。也就是說,給一個有k位數字的數加倍,你要知道結果數字是否只由原始數字中的數字排列組成。

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

思路

這題很簡單,就是普通的大數乘法模擬,要注意的是:不是判斷加倍前的每位數是否在加倍後的數中出現過,而是判斷是否由加倍前的每一位陣列成的。也就是說要統計數的個數(可能只有我一個人理解錯題意了,不過也只有測試點4出錯)正確理解題意之後這題就滿分AC

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string get_double(string);
int str1[10] = {0}; //記錄加倍前的每位數出現的頻數
int str2[10] = {0}; //記錄加倍後的每位數出現的頻數
int main()
{
	string str;
	cin >> str;
	for (int i = 0; i < str.size(); i++)
		str1[str[i] - '0']++; //統計頻數
	string d_str = get_double(str);
	for (int i = 0; i < d_str.size(); i++)
		str2[d_str[i] - '0']++;
	int flag = 0;
	for (int i = 0; i < 10; i++)
	{
		if (str1[i] != str2[i])
		{
			flag = 1;
			break;
		}
	}
	if (!flag)
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
	cout << d_str << endl;
	system("pause");
	return 0;
}
string get_double(string s) //模擬大數乘法
{
	string ans;
	int carry = 0;
	for (int i = s.size() - 1; i >= 0; i--)
	{
		int d = (s[i] - '0') * 2 + carry;
		carry = d / 10;
		d %= 10;
		ans = to_string((long long)d) + ans;
	}
	if (carry != 0)
		ans = "1" + ans;
	return ans;
}

相關文章