<MEMORY>Project Euler NO32

如果一个n位数使用了1到n中每个数字且只使用了一次,我们称其为pandigital。例如,15234这个五位数,是1到5pandigital的。

7254是一个不寻常的数,因为:39 × 186 = 7254这个算式的乘数,被乘数和乘积组成了一个1到9的pandigital组合。
找出所有能够组合成1到9pandigital的乘法算式中乘积的和。

提示: 有的乘积数字能够被多个乘法算式得到,所以在计算时要记得只计算它们一次。



分析:

a * b = c
1   2   
1   3 
1   4   4
2位 * 2 位  最多 4 位  (去掉)
2   3   4
3   3   3(去掉)

所以
1 < a < 99;
12 < b < 9999;


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


public class Problem32
{
	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 List<Integer> all = new ArrayList<>();
	static void howmany()
	{
		int sum = 0;
		for (int a = 1; a < 99; a++)
		{
			for(int b = 12; b < 9999; b++)
			{
				int c = a * b;
				if ((c + "").length() != 9 - (a + "").length() - (b + "").length() )
				{
					continue;
				}
				
				if (check(a + "" + b + c))
				{
					if (ishad(c))
					{
						sum += c;
					}
				}
			}
		}
		System.out.println(sum);
	}
	
	static boolean ishad(int n)
	{
		for (int i = 0; i < all.size(); i++)
		{
			if (n == all.get(i))
			{
				return false;
			}
		}
		
		all.add(n);
		return true;
	}
	
	static boolean check(String str)
	{
		char ch[] = str.toCharArray();
		for (int i = 0; i < str.length(); i++)
		{
			if (ch[i] == '0')
			{
				return false;
			}
			for (int j = i + 1; j < str.length(); j++)
			{
				if (ch[j] == '0')
				{
					return false;
				}
				
				if (ch[i] == ch[j])
				{
					return false;
				}
			}
		}
		
		return true;
	}
	
}

answer:  45228
time:  526

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值