把int转string 排序后再转成int就好
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int n,ans;
void convert(int num ,int & n1 ,int & n2) {
vector <int> ans;
n1 = 0; n2 = 0;
for (int i = 0; i < 4; i++) {
int digit = num % 10;
num /= 10;
ans.push_back(digit);
}
sort(&ans[0], &ans[0] + 4);
for (int i = 0; i < 4; i++) {
n1 *= 10;
n1 += ans[i];
n2 *= 10;
n2 += ans[3 - i];
}
}
int main() {
cin >> n;
int temp = n;
bool tag = true;
int pre = n % 10;
for (int i = 0; i < 3; i++) {
temp /= 10;
int digit = temp % 10;
if (pre != digit) {
tag = false;
break;
}
}
if (tag) {
printf("%4d - %4d = 0000\n", n, n);
}
else {
int n1, n2;
int ans = 0;
int pre = -1;
while (pre != ans) {
pre = ans;
convert(n, n1, n2);
ans = n2 - n1;
n = ans;
if(ans != pre)
printf("%04d - %04d = %04d\n", n2, n1, ans);
}
}
return 0;
}