---
title: "问题2: 打印\"水仙花数 \""
author: "elihe2011"
date: "2013-08-28T22:44:28Z"
tags: []
categories: ["编程语言"]
slug: "2"
draft: false
lastmod: "2013-08-28T22:49:04Z"
id: 1933045
url: "https://elihe2011.iteye.com/blog/1933045"
---

分析：水仙花数是指一个 n 位数 ( n≥3 )，它的每个位上的数字的 n 次幂之和等于它本身。例如：153是一个 "水仙花数 "，因为153=1的三次方＋5的三次方＋3的三次方

```java

public class Daffodils {
	public static void main(String[] args) {
		for (long n = 100; n < 1000; n++) {
			if (match(n)) {
				System.out.print(n + "\t");
			}
		}
	}

	private static boolean match(long n) {
		// 数字位数
		int count = (n + "").length();
		// 每一位数字
		long temp = 0;
		// 辗转相除的余数，即由数字分裂得到
		long num = n;
		// 每一位数字的count次方和
		long sum = 0;
		for (int i = count; i > 0; i--) {
			temp = num / (long) Math.pow(10, i - 1);
			num = num % (long) Math.pow(10, i - 1);
			sum += (long) Math.pow(temp, count);
		}
		return sum == n;
	}
}

```