java--for循环之水仙花数问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lcn_Lynn/article/details/72675141

什么是水仙花数

解析:
一个三位数,其各位数字的立方和是其本身
例如:
153 = 1*1*1+5*5*5+3*3*3
使用for循环
问题:
如何获取各位的数?
例如:
153--
个位3: 153 % 10       =3
十位5: 153 /10 %10     =5
百位1: 153 /10 /10 %10  =1
上代码:

package com.lcn.day04;


public class NarcissisticNumber {


	/**
	 * 水仙花数问题
	 */
	public static void main(String[] args) {
		System.out.println("100-1000中的水仙花数有:");
		for(int i=100;i<1000;i++){
			int ge  = i%10;
			int shi = i/10%10;
			int bai = i/10/10%10;
			
			//水仙花数判断要求
			if(i == (ge*ge*ge+shi*shi*shi+bai*bai*bai)){
				System.out.println(i);
			}
		}


	}


}

输出:
100-1000中的水仙花数有:
153
370
371
407

                                           

猜你喜欢

转载自blog.csdn.net/lcn_Lynn/article/details/72675141