水仙花数

简介: package com.tsxs.arithmetic;/** * 计算水仙花数.<br> * 水仙花数:一个n(n>=3)位数,它的每个位数上的数字的n次幂之和等于它本身.<br> * 例如:371=3^3+7^3+1^3.<br> * 思路:<br> * 1.数据的位数:操作数除以10的商的位数加1.<br&gt
package com.tsxs.arithmetic;
/**
 * 计算水仙花数.<br>
 * 水仙花数:一个n(n>=3)位数,它的每个位数上的数字的n次幂之和等于它本身.<br>
 * 例如:371=3^3+7^3+1^3.<br>
 * 思路:<br>
 *  1.数据的位数:操作数除以10的商的位数加1.<br>
 *  2.每个位数上的数:操作数每次除以10的余数.<br>
 *  3.字符串切割切换非算法,此处不使用.
 * */
public class DaffodilNumber {
	public static void main(String[] args) {
		for(int i = 100;i < 100000;i++){
			if(isDaffodilNumber(i)){
				System.out.println(i);
			}
		}
	}
	/**
	 * isDaffodilNumber:判断是否为水仙花数
	 * @param number 操作数
	 * @return boolean true为水仙花数
	 * */
	static boolean isDaffodilNumber(int number){
		//获取数据的位数
		int length = 0;
		//备份数据
		int temp1 = number;
		int temp2 = number;
		//保存各位次幂纸之和
		int sum = 0;
		//判断水仙花结果
		boolean isDaffodil = false;
		//位数
		while(temp1 / 10 > 0){
			temp1 /= 10;
			length++;
		}
		length++;
		//判断是否为水仙花
		for(int i = 0;i <= length;i++){
			sum+=Math.pow(temp2 % 10, length);
//			sum = (int) (sum + Math.pow(temp2 % 10, length));
			temp2/=10;
		}
		//如果和等于本身为水仙花
		if(sum == number){
			isDaffodil = true;
		}
		return isDaffodil;
	}
}


计算结果,100~100000,水仙花数:
 153
 370
 371
 407
 1634
 8208
 9474
 54748
 92727
 93084

 

注:此处写代码时,发现了一个小问题(jdk version:1.8.0_45),请看下边代码:
 sum+=Math.pow(temp2 % 10, length);
 sum = (int) (sum + Math.pow(temp2 % 10, length));
以上代码都正确执行.
1:Math.pow方法实现:public static native double pow(double a, double b);
2:Math.pow方法返回值为double和int进行"+"算数运算,运算结果为double,赋值int类型 的sum要进行强制类型转换.
3:i,j为数值型.
   运算规则:i+=j; //等价于 i = i + j; 

计算水仙花数,此处可见,精度不同,但赋值运算符"+="尽然已经做了隐式类型转换(自动类型转换).
4:精度变高,所占位数(bit)变长:
byte→short(char)→int→long→float→double
5:基本数据类型:

数据类型  名称      长度                     默认值     位数范围
boolean   布尔型   1字节(8位)           false        只有false、true
byte         字节型   字节(1byte=8bit)  0              -128~127 (-2^7~2^7-1)
char         字符型   2字节(16位)         '\u0000'    '\u0000'~'\uffff'
short        短整型   2字节(16位)         0              -32768~32767 (-2^15~2^15-1)
int            整型       4个字节(32位)     0              -2147483648~2147483647 (-2^31~2^31-1)
long         长整型   8个字节(64位)     0       -9223372036854774808~9223372036854774807(-2^63~2^63-1)
float         浮点型   4个字节(32位)     0.0f     3.402823e+38 ~ 1.401298e-45 (e+38是乘以10的38次方,e-45是乘以10的负45次方,e=10)
double     双精度型 8个字节(64位)   0.0d     1.797693e+308~ 4.9000000e-324

目录
相关文章
|
3天前
练习实例 - 水仙花数
【1月更文挑战第14天】水仙花数。
29 0
|
9月前
|
算法
求1000以内所有的水仙花数
求1000以内所有的水仙花数
|
9月前
wustojc4001判断水仙花数
wustojc4001判断水仙花数
34 0
|
11月前
|
算法
求水仙花数
求水仙花数
53 0
|
11月前
找出水仙花数
找出水仙花数
53 0
|
12月前
7-150 水仙花数
7-150 水仙花数
36 0
|
12月前
7-107 找出三位水仙花数
7-107 找出三位水仙花数
73 0
|
机器学习/深度学习 人工智能 算法
能被整除的数
能被整除的数
能被整除的数
HOW求两个数的最小公倍数?
HOW求两个数的最小公倍数?
94 0
HOW求两个数的最小公倍数?
|
机器学习/深度学习 算法 Windows
HOW求两个数的最大公约数?
HOW求两个数的最大公约数?
75 0
HOW求两个数的最大公约数?