关于最大乘积

最大乘积

问题描述:

把 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);
			}
		}
	}
	
	//是否只包含1~9这9个数字,而且每个数字只出现1次
	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);
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值