用Java实现水仙花数是指一个N位正整数(7≥N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 要求编写程序,计算所有N位水仙花数。 输入格式: 输入一个正整数N(3≤N≤7)。 输出格式: 按递增顺序输出所有N位水仙花数,每个数字占一行。
时间: 2023-10-23 18:22:51 浏览: 62
以下是Java实现水仙花数的代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int start = (int) Math.pow(10, n - 1); // 计算N位数的最小值
int end = (int) Math.pow(10, n) - 1; // 计算N位数的最大值
for (int i = start; i <= end; i++) {
int sum = 0;
int temp = i;
while (temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, n);
temp /= 10;
}
if (sum == i) { // 判断是否为水仙花数
System.out.println(i);
}
}
}
}
```
首先读入N,然后计算N位数的最小值和最大值。接下来逐个判断每个数是否为水仙花数。对于每个数,我们使用while循环将其各个位上的数字取出并计算其N次方的和。最后将结果与原数进行比较,如果相等则输出该数。