题目
一直循环相减即可,直到结果为6174或者四个数字相同就结束循环
题解 C++
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int cmp1(int a, int b) {
return a > b;
}
int cmp2(int a, int b) {
return a < b;
}
int main() {
int num;
cin >> num;
//循环计算
int cha;
do {
//分离四位
int saveNum = num;
int arr[4];
for (int i = 0; i < 4; i++) {
arr[i] = num % 10;
num /= 10;
}
//是否四位都相同
if (arr[0] == arr[1] && arr[1] == arr[2] && arr[2] == arr[3]) {
printf("%04d - %04d = %04d", saveNum, saveNum, 0);
system("pause");
return 0;
}
//大到小
sort(arr, arr + 4, cmp1);
int big = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
//小到大
sort(arr, arr + 4, cmp2);
int small = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
cha = big - small;
printf("%04d - %04d = %04d\n", big, small, cha);
num = cha;
} while (cha != 6174);
system("pause");
}