If we input a number formed by 4 digits and these digits are not all of one same value, then it obeys the following law. Let us operate the number in the following way:
(1) Arrange the digits in the way from bigger to smaller, such that it forms the biggest number that could be made from these 4 digits;
(2) Arrange the digits in the way from smaller to bigger, such that it forms the smallest number that could be made from these 4 digits (If there is 0 among these 4 digits, the number obtained may be less than four digits);
(3) Find the difference of these two numbers that is a new four digital number.
Repeat the above process, we can finally always get the result 6174 or 0.
Please write the program to realize the above algorithm.
因为题目用于判断4位数且4个数且不相同 ,所以我们需要判断输入的数是否为4位数且是否相同
我们可以用 x<1000||x>9999||x%1111==0 来判断
或 (s1 >= 1000 && s1 <= 9999 && s1 % 1111 != 0) 来判断
当最大的数减最小的数小于1000,那我们的最大数也应该小于1000
所以我们需要用
while(max>=x1*10)max/10 来使多乘的倍数去掉
因为min是从小到大所以我们不需要判断因为0*10还是0
我们可以写个函数来循环减来找到问我们想要的结果
判断条件
if (s < 1000 || s> 9999 || s % 1111 == 0) {
printf("No!!\n");
continue;
}
或
if (s >= 1000 && s <= 9999 && s % 1111 != 0) {
cnp(s);
} else {
printf("No!!\n");
}
函数
void cnp(int s) {
if (s == 6174 || s == 0) {
printf("Ok!! %d times\n", anx);
return;
}
anx++;
int s1 = s;
for (int i = 0; i < 4; i++) {
x[i] = s % 10;
s /= 10;
}
sort(x, x + 4);
int min = 0, max = 0;
for (int i = 0, j = 3; i < 4; i++, j--) {
min = min * 10 + x[i];
max = max * 10 + x[j];
}
while (max >= s1 * 10) 来判断max是否有多乘倍数
max /= 10;
printf("%d-%d=%d\n", max, min, max - min);
cnp(max - min); 如果当前不满足就继续找
}
代码
#include <iostream>
#include <algorithm>
using namespace std;
int x[4];
int anx = 0; 记录次数
void cnp(int s) {
if (s == 6174 || s == 0) {
printf("Ok!! %d times\n", anx);
return;
}
anx++;
int s1 = s;
for (int i = 0; i < 4; i++) {
x[i] = s % 10;
s /= 10;
}
sort(x, x + 4);
int min = 0, max = 0;
for (int i = 0, j = 3; i < 4; i++, j--) {
min = min * 10 + x[i];
max = max * 10 + x[j];
}
while (max >= s1 * 10)
max /= 10;
printf("%d-%d=%d\n", max, min, max - min);
cnp(max - min);
}
int main() {
int s;
while (scanf("%d", &s) && s != -1) {
anx = 0;
printf("N=%d:\n", s);
if (s < 1000 || s > 9999 || s % 1111 == 0) {
printf("No!!\n");
continue;
}
cnp(s);
}
}