7-10 JAVA-水仙花数 (10分)

水仙花数是指一个N位正整数(7≥N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 要求编写程序,计算所有N位水仙花数。

输入格式:

输入一个正整数N(3≤N≤7)。

输出格式:

按递增顺序输出所有N位水仙花数,每个数字占一行。

输入样例:

在这里给出一组输入。例如:

3

输出样例:

在这里给出相应的输出。例如:

153
370
371
407

代码块:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n= sc.nextInt();
		sc.close();
		int lb = (int)(Math.pow(10, n-1));
		int ub = (int)(Math.pow(10, n));
		int bites[] = new int[10];
		for(int i=0;i<bites.length;i++) {
			bites[i]=(int)Math.pow(i, n);
		}
		for(int i=lb;i<ub;i++) {
			int num =i;
			int result=0;
			while(num!=0) {
				result += bites[num%10];
				num /= 10;
			}
			if(result==i)
				System.out.println(i);
		}
	}

}
原创文章 14 获赞 12 访问量 1209

猜你喜欢

转载自blog.csdn.net/weixin_45713984/article/details/105403192
今日推荐