1)输入一个 n 位的数,先判断是否为水仙花数。如果是水仙花数,则调整这个
n 位数的各位数字的顺序,获取相同的 n 个数字所能组成的所有数,并按数
的大小进行排序后,找到其中最小的那个数。
2)可以求出所有 n 位数中的水仙花数,并按大小排序显示在界面上。
代码如下:
#include <stdio.h>
#include <math.h>
#include <process.h>
//冒泡排序
void bubble_sort(int a[],int n)
{
int i,j,t;
for (i=0;i<n-1;i++)
{
for (j=0;j<n-1-i;j++)
{
if(a[j] > a[j+1]) //从小到大,升序
{
t = a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
return ;
}
//判断是否是水仙花
int isSxh(int n,int p[],int *ws)
{
int s = 0;
int a = n;
int d = 0;
int i = 0;
while(a>0)
{
int d = a%10;
p[i] = d;
s += (d*d*d);
a = a/10;
i++;
}
*ws = i;
if(s == n)
return 1;
else
return 0;
}
int main()
{
int n,s=0,big=0;
int p[20],i,ws=0;
scanf("%d",&n);
if(!isSxh(n,p,&ws)) //不是水仙花数
{
printf("不是水仙花数\n");
return 0;
}
//处理水仙花数
bubble_sort(p,ws); //所有数按照从小到大排序
if(ws==3)
{
printf("%d ",p[0]*100+p[1]*10+p[2]);
printf("%d ",p[0]*100+p[2]*10+p[1]);
printf("%d ",p[1]*100+p[0]*10+p[2]);
printf("%d ",p[1]*100+p[2]*10+p[0]);
printf("%d ",p[2]*100+p[0]*10+p[1]);
printf("%d\n",p[2]*100+p[1]*10+p[0]);
}
s=0;
for(i=0;i<ws;i++)
s = s*10 + p[i];
printf("最小数是%d\n",s);
s = pow(10.0,ws-1); //n位最大数
big = pow(10.0,ws)-1; //n位最小数
//变量从最大的数到最小的数,并找出其中的水仙花数
for (i=big;i>=s;i--)
{
if (isSxh(i,p,&ws))
{
printf("%d ",i);
}
}
system("pause");
return 0;
}
#include <stdio.h>
#include <math.h>
int main()
{
int m;
int k;
int l;
int a;
l=0;
k=0;
for(m=100;m<1000;m++){
k=0;
l=m;
while(l>0){
k+= (int)pow(l%10,a);
l/=10;
}
if(m==k){
printf("%d\t",m);
}
}
return 0;
}