天天看點

PAT甲級A1023 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 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
           

題意:給定一個不超過20位的正整數n,讓你把n乘以2,然後判斷2倍的n是否為原來n的另一種排列組合(0-9每個數字出現的次數相同),如果是輸出Yes,否則輸出No,然後第二行輸出2倍的n。

思路:大整數加法,使用字元串存儲n,然後使用哈希表ht統計n每個數字的出現次數,最後如果2倍n的對應ht全部為0則說明n和2n是同一組數字的不同排列組合。最後别忘了加進位carry!

參考代碼:

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int ht[10]={0};
int main()
{
	string str,ans="";
	int carry=0;	//标記進位
	bool flag=true;	//标記是否滿足特性 
	cin>>str;
	for(int i=str.size()-1;i>=0;i--){
		int t=str[i]-'0';
		ht[t]++;
		t=2*t+carry;
		carry=t/10;
		ans+=t%10+'0';
		ht[t%10]--;
	}
	if(carry) {
		ans+=carry+'0';
		ht[1]--;
	}
	reverse(ans.begin(),ans.end());
	for(int i=0;i<10&&flag;i++) {
		if(ht[i]!=0)
			flag=false;
	}
	flag==true?printf("Yes\n"):printf("No\n"); 
	cout<<ans<<endl;
	return 0;
}