1. 程式人生 > 實用技巧 >PAT 甲級 1023 Have Fun with Numbers (20分)

PAT 甲級 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 withkdigits, 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

AC三部曲:1、[ 判斷數字進位 ]    2、[ vector記錄分類 ]   3、[sort後比較輸出 ]

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 vector<int> v, vv, s2; //v  double_v answer
 5 
 6 int main()
 7 {
 8     string s; cin >> s;//字串輸入
 9     int len = s.length();//數字位數
10     for(int i = 0; i < len; i++) v.push_back(s[i]-'0');//字元—>數字 加入v中
11     sort(v.begin(), v.end());//從小到大排序
12     
13     int next = 0;//進位標誌
14     for(int i = len-1; i >= 0; i--)  {
15         if( 2*(s[i]-'0') < 10 ) {   
16             int x = 2*(s[i]-'0') + next;//double後無法進位 + next(0)
17             vv.push_back(x); s2.push_back(x);
18             next = 0;
19         }
20         else {
21             int x = 2*(s[i]-'0') % 10 + next;//double後進位 + next(1)
22             vv.push_back(x); s2.push_back(x);
23             next = 1;
24         }
25     }
26     if(next) {//next == 1 因此double後的位數大於原數位數
27         cout << "No" << endl << "1";
28         for(int i = vv.size()-1; i >= 0; i--) cout << vv[i];
29     }
30     else {//前後位數相等
31         sort(vv.begin(), vv.end());
32         int flag = 1;
33         for(int i = 0; i < v.size(); i++) if(v[i] != vv[i]) { flag = 0; break; }
34         if(flag) cout << "Yes" << endl; 
35         else cout << "No" << endl;
36         for(int i = s2.size()-1; i >= 0; i--) cout << s2[i];
37     }
38     return 0;
39 }
View Code