PTA (Advanced Level)1023 Have Fun with Numbers
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 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以內的數字(由1~9組成),要求判斷這個數字加倍後的新數字是不是這個數字的某一種排列,如果是的化輸出Yes否則輸出No,之後輸出加倍後的數字。
由於數字最大位數為20位,超過了long long int的記錄範圍我們用數組num記錄這個數字,用數組cnt記錄num中1~9出現的次數,將num加倍後判斷其中1~9出現的次數是否發送改變,若沒有發送改變則證明加倍後的數字是原數字的某一種排列,反之則不是。
AC代碼
1 #include <bits/stdc++.h> 2 using namespace std; 3 int num[22]; 4 int cnt[10]; 5 string str; 6 void toInt(){ 7 for(int i = 0; i < str.size(); i++) 8 num[i] = str[i] - ‘0‘; 9 } 10 void getCnt(){ 11 for(int i = 0; i < str.size(); i++) 12 cnt[num[i]]++; 13 } 14 bool judge(int carry){ 15 if(carry != 0) //如果最高位進位不為零,則證明加倍後的數字比原數字多一位,那麽其肯定不是原數字的一個排列 16 return false; 17 for(int i = 0; i < str.size(); i++) 18 cnt[num[i]]--; 19 for(int i = 1; i <= 9; i++){ //判斷新的num中1~9的數量是否和加倍前一樣 20 if(cnt[i] != 0) 21 return false; 22 } 23 return true; 24 } 25 int doubleNumber(){ //將數組num加倍並返回最高位進位 26 int carry = 0; 27 for(int i = str.size() - 1; i >= 0; i--){ 28 int temp = num[i]; 29 num[i] = (2 * temp + carry) % 10; 30 carry = 2 * temp / 10; 31 } 32 return carry; 33 } 34 int main() 35 { 36 cin >> str; //輸入數字 37 toInt(); //將輸入的數字轉化為數組 38 getCnt(); //獲取數組中1~9出現的次數 39 int carry = doubleNumber(); //將num加倍carry記錄最高位的進位 40 if(judge(carry)){ //判斷加倍後的數字是否為原數字的某一個排列 41 printf("Yes\n"); 42 43 }else 44 printf("No\n"); 45 if(carry != 0) //判斷是否需要輸出進位 46 printf("%d", carry); 47 for(int i = 0; i < str.size(); i++) //輸出加倍後的數組num 48 printf("%d", num[i]); 49 printf("\n"); 50 return 0; 51 }
PTA (Advanced Level)1023 Have Fun with Numbers