水仙花問題的求解

---------------------------------------天道酬勤

打印出所有的 "水仙花數 ",所謂 "水仙花數 "是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個 "水仙花數 ",因爲153=1的三次方+5的三次方+3的三次方。

注:解決這個問題關鍵就在於如何獲取每一位的數字,對於十進制數,模10即可得低位數字

代碼如下:

import java.util.ArrayList;
import java.util.ListIterator;
class Test11
{
	public static void main(String[] args)
	{
		Test11.display(1,1000);
	}
	public static boolean judge(long num)
	{
		ArrayList<Byte> list=new ArrayList<Byte>();
		if(1==num)
			return true;
		if(num<10)
			return false;
		long temp=num;
		while(temp>0)
		{
			list.add((byte)(temp%10));
			temp=temp/10;
		}
		temp=0;
		for(ListIterator<Byte> it=list.listIterator();it.hasNext();)
		{
			Byte i=it.next();
			temp=temp+i*i*i;
		}
		if(temp==num)
			return true;
		return false;
	}
	public static void display(long i,long j)
	{
		for(long k=i;k<=j;k++)
		{
			if(Test11.judge(k))
				System.out.println(k);
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章