最大乘积
问题描述:
把 1~9 这9个数字分成两组,中间插入乘号,
有的时候,它们的乘积也只包含1~9这9个数字,而且每个数字只出现1次。
比如:
984672 * 351 = 345619872
98751 * 3462 = 341875962
9 * 87146325 = 784316925
...
符合这种规律的算式还有很多,请你计算在所有这些算式中,乘积最大是多少?
注意,需要提交的是一个整数,表示那个最大的积,不要填写任何多余的内容。
(只提交乘积,不要提交整个算式)
答案:839542176
解决方案:
import java.math.*;
import java.util.*;
public class Main {
static BigInteger sum = new BigInteger("0");
public static void swap(int[] num, int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
public static void perm(int[] num, int start, int end) {
if (start == end) {
mul(num);
} else {
for (int i = start; i < end; i++) {
swap(num, start, i);
perm(num, start + 1, end);
swap(num, start, i);
}
}
}
public static boolean check(BigInteger temp){
String s = temp.toString();
HashSet<Character> set = new HashSet<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i) == '0')
return false;
set.add(s.charAt(i));
}
if(set.size() == 9)
return true;
return false;
}
public static void mul(int[] num) {
BigInteger a = new BigInteger("0");
BigInteger b = new BigInteger("0");
BigInteger t = new BigInteger("10");
for (int i = 0; i < num.length; i++) {
a = a.multiply(t).add(new BigInteger(""+num[i]));
for (int j = i + 1; j < num.length; j++) {
b = b.multiply(t).add(new BigInteger(""+num[j]));
}
BigInteger temp = a.multiply(b);
if(check(temp))
sum = sum.max(temp);
b = new BigInteger("0");
}
}
public static void main(String[] args) {
int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
perm(num, 0, num.length);
System.out.println(sum);
}
}