数字黑洞(20)

主要字符数组到数字之间的转换太费劲了, 忘记有stringstream这个东西了

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
  
using namespace std;
  
 string int2string(int ival)
{
    stringstream stream;       //创建一个stringstream,  即可以用来输入,也可用来输出数据
    stream << ival;               //将int型值传给stringstream,
    return stream.str();         //stringstream的成员函数str()  返回一个相应的字符串
}
  
int main()
{
    string num_str;
    cin >> num_str;
    if(num_str.size() != 4)  // 输入数据不满4位,则要添加0补满4位
    {
        num_str.append(4 - num_str.size(), '0');
    }
    while(true)
    {
        // 先检查数字字符是否全部一样
        if(num_str.find_first_not_of(num_str[0]) == string::npos)
        {
            cout << num_str << " - " << num_str << " = " << "0000" << endl;
            break;    // 结束循环
        }
        // 数字字符升序排序
        sort(num_str.begin(), num_str.end());
        int num_ascend = stoi(num_str);
        // 数字字符降序排序
        reverse(num_str.begin(), num_str.end());
        int num_descent = stoi(num_str);
        if(num_ascend != num_descent)  // 四位数字不全相同情况
        {
            if(num_descent - num_ascend == 6174)
            {
                cout << num_descent << " - " << num_ascend << " = "
                     << 6174 << endl;
                break;   // 结束循环
            }
            else    //差不为6174
            {
                string num_ascend_str = int2string(num_ascend);
                if(num_ascend_str.size() != 4)  // 控制输出的格式,必须有4位填充满
                    num_ascend_str.insert(0, 4 - num_ascend_str.size(), '0');
                cout << num_descent << " - " << num_ascend_str << " = "
                     << num_descent - num_ascend << '\n';
                num_str = int2string(num_descent - num_ascend);
            }
        }
    }
  
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值