如果一个n位数使用了1到n中每个数字且只使用了一次,我们称其为pandigital。例如,15234这个五位数,是1到5pandigital的。
7254是一个不寻常的数,因为:39 × 186 = 7254这个算式的乘数,被乘数和乘积组成了一个1到9的pandigital组合。
找出所有能够组合成1到9pandigital的乘法算式中乘积的和。
answer: 45228
time: 526
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