Project Euler NO38

將192與1,2,3分別相乘得到:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
將這三個乘積連接起來我們得到一個1到9的pandigital數, 192384576。我們稱 192384576是192和 (1,2,3)的連接積。
通過將9與1,2,3,4和5相乘也可以得到pandigital數:918273645,這個數是9和(1,2,3,4,5)的連接積。

用一個整數與1,2, ... , n(n大於1)的連接積構造而成的1到9pandigital數中最大的是多少?



public class Problem38
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		howmany();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static void howmany()
	{
		int max = 0;
		for (int i = 1; i < 99999; i++)
		{
			String str = "";
			for (int j = 1; str.length() < 9; j++)
			{
				str += i * j + "";
			}
			if (str.length() == 9 && check(str))
			{
				int t = Integer.parseInt(str);
				if (max < t)
				{
					max = t;
				}
			}
		}
		
		System.out.println(max);
	}
	
	static boolean check(String str)
	{
		char ch[] = str.toCharArray();
		for (int i = 0; i < ch.length; i++)
		{
			if (ch[i] == '0')
			{
				return false;
			}
			for (int j = i + 1; j < ch.length; j++)
			{
				if (ch[j] == '0')
				{
					return false;
				}
				if (ch[i] == ch[j])
				{
					return false;
				}
			}
		}
		
		return true;
	}
	
}



answer:  932718654
time:  94

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