001:6174问题

问题:

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 }

 

转载于:https://www.cnblogs.com/chenjz1993/p/7280580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值