一、技术总结
- 这一题主要学习到两个知识点,一个是stoi函数的使用,之前已经讲过了,可以将一个字符串转化为10进制的数字;
- 还有就是字符串string中insert函数的使用,可以str.insert(0, num, '0');意思是在下标为0处插入num个字符‘0’;
- 还有就是使用do{}while;循环。
二、参考代码
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(char a, char b) {return a > b;}
int main(){
string s;
cin >> s;
s.insert(0, 4 - s.length(), '0');
do{
string a = s, b = s;
sort(a.begin(), a.end(), cmp);
sort(b.begin(), b.end());
int result = stoi(a) - stoi(b);
s = to_string(result);
s.insert(0, 4 - s.length(), '0');
cout << a << " - " << b << " = " << s << endl;
}while(s != "6174" && s != "0000");
return 0;
}