实例三十九:卡布列克运算
问题描述:
所谓卡布列克运算是指对任意一个四位数,只要它们各个位上的数字不完全相同,就是这样的规律:
(1)把组成这个四位数的四个数字重新生成最大的四位数;
(2)把组成这个四位数的四个数字重新生成最小的四位数(若四个数字中含有0,则此四位数可小于四位);
(3)求出以上两数之差,得到一个新的四位数。
重复以上过程,总能得到最后的结果为6174。
试编写卡布列克运算的验证程序。
The so-called Kabrek operation refers to any four digits, as long as the numbers on their respective bits are not exactly the same, this is the law:
(1) Regenerate the four digits that make up the four digits to the maximum four digits;
(2) Regenerate the smallest four digits of the four digits that make up the four digits (if the four digits contain 0, the four digits can be less than four digits);
(3) Find the difference between the above two numbers and get a new four-digit number.
Repeat the above process and always get the final result of 6174.
Try writing the verification program for the Kabrek operation.
算法思路:
分三个模块解决:
(1)将一个四位数的每一位数字按从大到小(或从小到大)的顺序放到一个一维数组中;
(2)将(1)中有序数组从左到右(或从右到左)组成一个最大的四位数;
(3)将(1)中有序数组从右到左(或从左到右)组成一个最小的四位数;
It is solved by three modules:
(1) Put each four-digit number in a one-dimensional array from large to small (or small to large);
(2) Forming an ordered array in (1) from left to right (or from right to left) to form a maximum four digits;
(3) Forming an ordered array in (1) from right to left (or from left to right) to form a minimum four-digit number;
/*实例三十九:卡布列克运算*/
#include<stdio.h>
int idigit(int n,int a[4]) //取得四位数,并按照从大到小的顺序排列
{
int i=0,j,t;
for(i=0;i<4;i++)
{
a[i] = n % 10;
n = n / 10;
}
for(i=0;i<3;i++) //比较四个数(比三次),并从大到小依次存放
for(j=i+1;j<4;j++)
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
return 1;
}
int getmin(int n) //重新生成最小的四位数m
{
int a[4],i,j,t,m=0; //数组;两个循环变量;各位置值t;传递继承值m;
idigit(n,a);
for(i=3;i>=0;i--) //数组的最小情况(倒着)
{
t = 1;
for(j=0;j<i;j++) //循环3+2+1+0=6次
t *= 10;
m += t * a[i];
}
return m;
}
int getmax(int n) //重新生成最大的四位数m
{
int a[4],i,j,t,m=0;
idigit(n,a);
for(i=0;i<4;i++)
{
t = 1;
for(j=0;j<3-i;j++)
t *= 10;
m += t * a[i];
}
return m;
}
int main()
{
int n;
printf("Please enter a four digit number that is not the same as each digit:\n");
scanf("%d",&n);
while(n!=6174)
{
printf("%4d - %4d = %4d\n",getmax(n),getmin(n),getmax(n)-getmin(n));
n = getmax(n) - getmin(n);
}
return 0;
}
程序心得:
本次运用到四位数的分离排序和求最小数和最大数的方法,我们将它们设计成为不同的独立模块。
This time we applied four-digit separation ordering and the method of finding the minimum and maximum numbers, we designed them into different independent modules.
拓展思考:
1.实际上可以直接将求最大最小的算法写在一块(主要解决返回两个值的问题,考虑用数组和指针处理解决)。
1. In fact, you can directly write the algorithm that seeks the largest and the smallest (mainly solve the problem of returning two values, consider solving with array and pointer processing).
2.能否将程序段Can you change block
for(i=0;i<4;i++)
{
a[i] = n % 10;
n = n / 10;
}
改为to
do
{
a[i++] = n % 10;
}while((n/=10)!=0)