PAT 乙级 1019
题目
题目地址:PAT 乙级 1019
思路
本题没有考虑到小于1000的情况,当小于1000的时需要给vector的向量中推入0,直到向量中有四位数字,之后再进行排序并进行相关计算
代码
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 #include <cmath> 5 using namespace std; 6 7 bool compare(int a, int b) { 8 return a > b; 9 } 10 11 int main() { 12 vector<int> num; 13 int n = 0; 14 cin >> n; 15 while (1) { 16 int chu = n, yu = 0; 17 while (chu >= 10) { 18 yu = chu % 10; 19 chu /= 10; 20 num.push_back(yu); 21 } 22 num.push_back(chu); 23 if (num.size() < 4) { 24 for (int i = num.size(); i < 4; i++) 25 num.push_back(0); 26 } 27 sort(num.begin(), num.end(), compare); 28 int large = 0; 29 int jie = num.size() - 1; 30 for (int i = 0; i < num.size(); i++) { 31 large += num[i] * pow(10, jie); 32 jie--; 33 } 34 if (large < 1000) { 35 if (large > 100) 36 cout << '0'; 37 else if (large > 10) 38 cout << "00"; 39 else 40 cout << "000"; 41 } 42 cout << large << " - "; 43 sort(num.begin(), num.end()); 44 int little = 0; 45 jie = num.size() - 1; 46 for (int i = 0; i < num.size(); i++) { 47 little += num[i] * pow(10, jie); 48 jie--; 49 } 50 if (little < 1000) { 51 if (little > 100) 52 cout << '0'; 53 else if (little > 10) 54 cout << "00"; 55 else 56 cout << "000"; 57 } 58 cout << little << " = "; 59 if (large - little < 1000) { 60 if (large - little > 100) 61 cout << '0'; 62 else if (large - little > 10) 63 cout << "00"; 64 else 65 cout << "000"; 66 } 67 cout << large - little << endl; 68 if (large - little == 6174) 69 break; 70 else if (large == little) 71 break; 72 else { 73 n = large - little; 74 num.clear(); 75 } 76 } 77 78 return 0; 79 }