1 //--------------------C_Style---------------------- 2 3 #include<stdio.h> 4 #include<string.h> 5 const int maxn = 3000; 6 7 int get_next(int n) 8 { 9 char str[10]; 10 sprintf(str, "%d", n); //将%d的n转换成字符串存入到str中 11 int size = strlen(str); 12 for(int ix = 1; ix != size; ++ix) //降序 13 { 14 int key = str[ix], index = ix -1; 15 for(; index >=0 && str[index] < key; --index) 16 str[index+1] = str[index]; 17 str[index+1] = key; 18 } 19 int a = 0; 20 sscanf(str, "%d", &a); //将字符串str转换成%d,存入到a中 21 int index = size-1; 22 for(ix = 0; ix < size/2, index >= size/2; ++ix, --index) 23 { 24 int t; 25 t = str[ix]; 26 str[ix] = str[index]; 27 str[index] = t; 28 } 29 int b = 0; 30 sscanf(str, "%d", &b); 31 return a-b; 32 } 33 int main() 34 { 35 int n; 36 scanf("%d", &n); 37 printf("%d", n); 38 while(get_next(n) !=n) 39 { 40 printf("->%d", get_next(n)); 41 n = get_next(n); 42 } 43 printf("->%d\n", n); 44 return 0; 45 }
1 //------------------------------------C++_Style--------------------------------------------- 2 #include<iostream> 3 #include<vector> 4 #include<sstream> 5 using namespace std; 6 7 int getnext(int n) 8 { 9 string str; 10 stringstream stream; 11 stream << n; //将n读入流stream中 12 stream >> str; //将n存入string对象中(相当于将整型转化为string) 13 stream.clear(); //重置stream内部状态 14 for(string::size_type i = 1; i != str.size(); ++i) //升序排序,得到最小值 15 { 16 char key = str[i]; 17 string::size_type j = i-1; 18 for(; j >= 0 && str[j] > key; --j) 19 str[j+1] = str[j]; 20 str[j+1] = key; 21 } 22 stream.str(""); //清空stream对象 23 stream << str; //将string对象存入整型 24 int min; 25 stream >> min; //将string转化为整型 26 stream.clear(); 27 stream.str(""); 28 //倒置stream对象得到最大值 29 for(string::size_type i = 0, j = str.size()-1; i < str.size()/2; ++i, --j) 30 { 31 char t; 32 t = str[i]; 33 str[i] = str[j]; 34 str[j] = t; 35 } 36 stream << str; 37 int max; 38 stream >> max; //转化成整型数 39 return max - min; 40 } 41 42 int find(const vector<int> &ivec, int n) //查找是否已存在 43 { 44 for(vector<int>::size_type i = 0; i != ivec.size()-1; ++i) 45 if(ivec[i] == n) 46 return 1; 47 return 0; 48 } 49 int main() 50 { 51 int n; 52 vector<int> ivec; 53 while(cin >> n) 54 { 55 ivec.push_back(n); 56 cout << n; 57 while(!find(ivec, getnext(n))) 58 { 59 cout << "->" << getnext(n); 60 ivec.push_back(getnext(n)); 61 n = getnext(n); 62 } 63 } 64 return 0; 65 }