題目鏈接
https://www.nowcoder.com/pat/6/problem/4045
代碼
#include<iostream>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<string.h>
#define LENGTH 4
using namespace std;
bool myfun(int i, int j) {
return i>j;
}
int main() {
int n, flag = 1;
int a[4];
memset(a, 0, sizeof(a));
scanf("%d", &n);
int result = n;
while(result != 6174 || flag) {
int i=0;
int big_value=0, small_value=0;
while(i < LENGTH) {
a[i] = result % 10;
result /= 10;
i++;
}
if( (a[0] == a[1]) && (a[0]== a[2]) && (a[0]== a[3])) {
cout << setw(4) << setfill('0') << n << " - " << setw(4) << setfill('0') << n << " = " << setw(4) << setfill('0') << "0000" << endl;
break;
}
sort(a, a+LENGTH, myfun);
for(int i=0; i<LENGTH; i++) {
big_value += a[i] * pow(10, LENGTH-i-1);
small_value += a[LENGTH-i-1] * pow(10, LENGTH-i-1);
}
result = big_value - small_value;
cout << setw(4) << setfill('0') << big_value << " - " << setw(4) << setfill('0') << small_value << " = " << setw(4) << setfill('0') << result << endl;
flag = 0;
}
return 0;
}