- import java.util.Scanner;
- public class 水仙花数2 {
- private static Scanner scan;
- public static void main(String[] args) {
- scan = new Scanner(System.in);
- int n = scan.nextInt();
- long startTime = System.currentTimeMillis();
- for (int i = 10; i <= n; i++) {
- if (isDaffodilNumber(i)) {
- System.out.println(i + " 是水仙花数.");
- }
- }
- long endTime = System.currentTimeMillis();
- System.out.println("运行时间是: " + (endTime - startTime));
- }
- private static boolean isDaffodilNumber(int i) {
- int s = 0;
- int n = (i + "").length(); // 计算数字串的长度
- for (int j = 1; j <= n; j++) { // 循环处理数字串
- int t1 = (int) (i / Math.pow(10, j - 1)); // 截取数字串,从前往后
- int t2 = (int) (Math.pow((t1 % 10), n)); // 提取最后一位数字,计算其n次方
- s += t2;
- }
- if (s == i) {
- return true;
- } else {
- return false;
- }
- }
- }
复制代码
|