南洋理工OJ——57题 6174问题

来源:互联网 发布:拉塞尔夏季联赛数据 编辑:程序博客网 时间:2024/04/29 19:55

思路:

1. 排序:将输入的字符串str1(string)从大到小排序,然后用另一个str2存str1的倒序

2. 类型转换:

  • string -> int :
int n;string str;cin>>str;n = atoi(str.c_str());
  • int -> string :
int n;string str;cin>>n;stringstream ss;ss>>n;ss<<str;

3.计算:sub = str1 - str2

4.计数:记录变成6174的变形次数

代码如下:

#include <iostream>#include <string>#include <sstream>#include <stdlib.h>using namespace std;class TheNum{private:    string num;    string Fnum;    int numUp,numDown;    int sub;    int cont;public:    TheNum()        //构造函数里对数据成员初始化    {        numUp = 0;        numDown = 0;        cont = 1;    }    void set(string n);   //设置数据成员的数值    void order();      //排序    void flip();       //倒序    void toInt();      //类型转换    void subtract();    //计算    int counter();      //计数    void toString();    //类型转换};void TheNum::set(string n){    num = n;}void TheNum::order(){    char t;    for (int i = 0; i < 4; i++)    {        for (int j = i; j < 4; j++)        {            if (num[i] < num[j])            {                t = num[i];                num[i] = num[j];                num[j] = t;            }        }    }}void TheNum::flip(){    int j = 0;    for (int i = 3; i >= 0; i--)    {        Fnum[j] = num[i];        j++;    }}void TheNum::toInt(){    numUp = atoi(num.c_str());    numDown = atoi(Fnum.c_str());}void TheNum::subtract(){    sub = numUp - numDown;}int TheNum::counter(){    do    {        toString();        order();        flip();        toInt();        subtract();        cont++;    }while (sub != 6174);    cont += 1;    return cont;}void TheNum::toString(){    stringstream ss;    ss<<sub;    ss>>num;}int main(){    int n;    cin>>n;    while (n--)    {        string input;        cin>>input;        TheNum pro;        pro.set(input);        pro.order();        pro.flip();        pro.toInt();        pro.subtract();        cout<<pro.counter()<<endl;    }}

南洋理工OJ链接

0 0
原创粉丝点击