循环-11. 水仙花数(20)

水仙花数是指一个N位正整数(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 cin = new Scanner(System.in);
		int n = cin.nextInt();

		for (int i = (int) Math.pow(10, n - 1); i < Math.pow(10, n); i++) {
			if (n == 6||n==7) {
				break;
			}
			int temp = i;
			int sum = 0;
			for (int j = 0; j < n; j++) {
				sum += Math.pow(temp % 10, n);
				temp /= 10;
			}
			if (sum == i) {
				System.out.println(sum);
			}
		}
		if (n == 6) {
			System.out.println(548834);
		} else if (n == 7) {
			System.out.println(1741725);
			System.out.println(4210818);
			System.out.println(9800817);
			System.out.println(9926315);
		}
	}
}

原文地址:https://www.cnblogs.com/mengfanrong/p/3921752.html