水仙花数(Java)

题目:

 * 求出0〜999之间的所有“水仙花数”并输出。“水仙花数”是指一个三位数,
 * 其各位数字的立方和确好等于该数本身,如;153=1+5+3?,则153是一个“水仙花数” 
 * 
 * 在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),
 * 是指一N位数,其各个数之N次方和等于该数。 
 * 例如153就是三位数的水仙花数,其各个数之立方和等于该数: 
 * 153 = 1^3 + 5^3 + 3^3。 

思路:

分别求数字中各位数字,判断乘方和是否等于原数字

代码:
 

package com.datastructure.other;

import java.util.ArrayList;
import java.util.List;

/**
 * 求出0〜999之间的所有“水仙花数”并输出。“水仙花数”是指一个三位数,
 * 其各位数字的立方和确好等于该数本身,如;153=1+5+3?,则153是一个“水仙花数” 
 * 
 * 在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),
 * 是指一N位数,其各个数之N次方和等于该数。 
 * 例如153就是三位数的水仙花数,其各个数之立方和等于该数: 
 * 153 = 1^3 + 5^3 + 3^3。 
 *
 */
public class NarcissisticNumber {

	/**
	 * 获取0-999之前的水仙花数 
	 */
	public static List<Integer> getNarcissisticNumber() {
		List<Integer> lst = new ArrayList<>();
		
		int start = 0;
		int end = 999;
		
		for (int i = start; i <= end; i++) {
			if (isNarcissisticNumber(i, start, end)) {
				lst.add(i);
			}
		}
		
		return lst;
	}
	
	private static boolean isNarcissisticNumber(int num, int start, int end) {
		if (num < start || num > end) {
			return false;
		}
		
		// 获取数字的位数
		int count = 0;
		if (num < 10) {
			count = 1;
		} else if (num < 100) {
			count = 2;
		} else {
			count = 3;
		}
		
		int i = num;
		int sum = 0;
		while (i > 0) {
			// 最后一位数字的乘方
			sum += Math.pow(i % 10, count);
			// 数字除以10
			i /= 10;
		}
		
		return sum == num;
	}
	
	public static void main(String[] args) {
		System.out.println(getNarcissisticNumber());
	}

}

参考:

水仙花数:https://blog.csdn.net/wang_0712/article/details/80279806

扩展:

21位的水仙花数:https://blog.csdn.net/bear_huangzhen/article/details/78465111

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/88809380