问题:
6174猜想:一个任意的四位正整数(全相同的除外,如1111)。
将数字重新组合成一个最大的数和最小的数相减,重复这个过程,最多七步,必得6174。
输入:一个四位数
输出:操作的序列,直到出现循环
1 // C++: 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 #include <map> 6 #include <set> 7 // C: 8 #include <cstring> 9 #include <stdio.h> 10 #include <ctype.h> 11 #include <stdlib.h> 12 #include <math.h> 13 using namespace std; 14 15 /* 16 1.输入的是一个四位数(字符串存储), 17 18 2.给字符串的字符排序,找出最大数max和最小数min, 19 20 3.将最大数和最小数相减,用来代替原来数(int),转成字符串; 21 */ 22 23 24 25 int main() 26 { 27 28 set<int> iset; 29 30 string str; 31 cin>>str; 32 bool flag =true; 33 int next; 34 35 next = atof(str.c_str()); 36 cout<<next; 37 iset.insert(next); 38 39 while( flag ){ 40 int len=str.length(); 41 //给这个四位数排序,从大到小 42 for(int i=0;i<len;i++){ 43 for(int j=i+1;j<len;j++){ 44 if(str[i] < str[j]){ 45 int tmp=str[i]; 46 str[i]=str[j]; 47 str[j]=tmp; 48 } 49 } 50 } 51 // 得到max_和min_ 52 // 例如:str[4]="4321" 53 double max_ = atof(str.c_str()); 54 55 for(int i=0;i<len/2;i++){ 56 char c=str[i]; 57 str[i]=str[len-i-1]; 58 str[len-i-1]=c; 59 } 60 61 double min_ = atof(str.c_str()); 62 next = max_ - min_ ; 63 64 auto it=iset.find(next); 65 if( it== iset.end() ){ 66 cout<<"-->"<<next; 67 iset.insert(next); 68 char ch[10]; 69 sprintf(ch,"%d",next); 70 str=string(ch); 71 } 72 else{ 73 return 0; 74 } 75 } 76 77 78 return 0; 79 }