主要字符数组到数字之间的转换太费劲了, 忘记有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;
}