【详细分析】1023 Have Fun with Numbers (20 分)_20行代码AC
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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
最開始把題看錯。。 以為輸出No后不需要輸出序列, 來來回回折騰了一個小時才A掉。 大意啦沒有閃(我可真蠢=_=|| ,乙級中文題都容易出錯,何況英文題)。
優化:只需開一個數組即可。遍歷輸入數字時++,遍歷其double數字時- -。最后判斷是否為0即可。
#include<bits/stdc++.h> using namespace std;int a[30];int main() {string s, double_s; cin >> s;int carry = 0, x = 0;for(int i = s.size()-1; i >= 0; i--) {a[s[i]-'0']++; x = ((s[i]-'0')*2+carry) % 10;carry = ((s[i]-'0')*2+carry)/10;double_s.insert(0, 1, '0'+x);a[x]--;}if(carry > 0) { a[carry]--; double_s.insert(0, 1, '0'+carry); }bool flag = false;for(int i = 0; i < 30; i++) if(a[i] != 0) flag = true;cout << (flag?"No":"Yes") << '\n' << double_s << '\n';return 0; }
耗時:
總結
以上是生活随笔為你收集整理的【详细分析】1023 Have Fun with Numbers (20 分)_20行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【分析】1021 Deepest Roo
- 下一篇: 【题意分析】1024 Palindrom