代碼
#include "stdafx.h"
typedef int (* pfun)(int a,int b);
int IsNumberEqual(int number) ;
void ntos (int number, int c[]) ;
void sort (int a[ ],pfun pf );
int getmaxn(int a[ ]);
int getminn(int b[ ]);
int asc(int a,int b) {return (a>b?1:0);}
int desc(int a,int b){return (a<b?1:0);}
int main(int argc, char* argv[])
{
int num=0;
printf("Please enter a number:");
scanf("%d",&num);
//IsNumberEqual調用時若數不為4位,或有危險,故放最後,短路返回
while( num<1000 || num>9999 || IsNumberEqual(num) ){
printf("invalid number :%d,try again:\n",num);
scanf("%d",&num);
}
int arr[4],max,min;
do{
ntos(num,arr);
max=getmaxn(arr);
printf("max=%d,",max);
min=getminn(arr);
printf("min=%d\n",min);
num=max-min;
}while(num!=6174);
printf("\n max(%d)-min(%d)=%d \n",max,min,max-min);
printf("\ndone");
return 0;
}
//用函數 int IsNumberEqual(int number) 檢查輸入的整數number各數位是否互不相等,
//有相等傳回值為1否則為0;
int IsNumberEqual(int number)
{
int a[4]={0,};
ntos(number,a);
int iRes=0;
for(int i=0;i<4;++i){
for(int j=i+1;j<4;++j){
if( a[i]==a[j] ){
iRes=1;
break;
}
}
if(iRes==1)break;
}
return iRes;
}
//用函數(void ntos (int number, int c[]) )把四位元整數number各位元碼分別存入數組c
void ntos (int number, int c[])
{
for(int i=0;number>0;++i){
c[i]=number%10;
number/=10;
}
}
//用函數( void sort (int a[ ] )對4個元素的數組a排序(升序或降序都可以);
void sort (int a[ ],pfun pf )
{
//選擇法
for(int i=0;i<4;++i){
for(int j=i+1;j<4;++j){
if( pf(a[i],a[j]) ){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
//傳回值為最大值
int getmaxn(int a[ ])
{
int sum=0,pow=1;
sort(a,desc);
for(int i=3;i>=0;--i,pow*=10){
sum+=a[i]*pow;
}
return sum;
}
//傳回值為最小值
int getminn(int a[ ])
{
int sum=0,pow=1;
sort(a,asc);
for(int i=3;i>=0;--i,pow*=10){
sum+=a[i]*pow;
}
return sum;
}