JAVA利用方法写输出 1-n 中的自幂数
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8a55311296f696dd09cf0ae0762ffd74.png)
import java.util.Scanner;
import java.lang.Math;
public class print {
public static void main(String[] args) {
System.out.println("输入范围(上限):");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("符合条件的有:");
print1(num);
}
public static void print1(int num){
for(int i = 0 ; i<= num ; i++){
int count = 0 ;
int tmp = i ;
while(tmp!=0){
count++ ;
tmp/=10 ;
}
tmp = i ;
long sum = 0L ;
while(tmp!=0){
sum+= Math.pow (tmp%10,count);
tmp/=10;
}
if(sum==i){
System.out.print(" "+i+" ");
}
}
}
}
测试:
输入范围(上限):
99999
符合条件的有:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084
代码中注意利用for循环从0开始进行第一个while是为了得到位数,第二个while是为了获得每一位,并且进行成分,幂就是第一个while所得到的,以此一直到最后输入的上限范围。