[蓝桥杯决赛][2018年第九届真题]最大乘积(Java代码)

标题:最大乘积

把 1~9 这9个数字分成两组,中间插入乘号,
有的时候,它们的乘积也只包含1~9这9个数字,而且每个数字只出现1次。

比如:
984672 * 351 = 345619872
98751 * 3462 = 341875962
9 * 87146325 = 784316925
...

符合这种规律的算式还有很多,请你计算在所有这些算式中,乘积最大是多少?

注意,需要提交的是一个整数,表示那个最大的积,不要填写任何多余的内容。
(只提交乘积,不要提交整个算式)

答案:839542176

import java.text.DecimalFormat;
import java.util.Stack;

public class Main_2 {
	public static int num[][] = new int[362880][9]; //9!=362880
	public static int i=0;
	public static void perm(int[] array, Stack<Integer> stack) {//全排列函数
        if(array.length <= 0) {
        	//进入了叶子节点,栈中内容就是一种全排列
            int j=0;
            //遍历栈
            for(Integer x : stack) {
            	num[i][j++] = x;
            }
            i++;
        } else {
            for (int i = 0; i < array.length; i++) {
            	//tmepArray是一个临时数组
                int[] tempArray = new int[array.length-1];
                //System.arraycopy(原数组,原数组开始位置,目标数组,目标数组开始位置,长度);
                System.arraycopy(array,0,tempArray,0,i); //0~i-1
                System.arraycopy(array,i+1,tempArray,i,array.length-i-1); //i+1~len-1
                //栈先进后出
                //把第i项压入堆栈顶部
                stack.push(array[i]);
                perm(tempArray,stack);
                stack.pop();
            }
        }
    }
	public static void main(String[] args) {
		int array[] = {1,2,3,4,5,6,7,8,9};
		Stack<Integer> stack = new Stack<Integer>();//栈先进后出
		perm(array,stack);
		long max = 0;//存储乘积最大值
		for(int i=0;i<362880;i++) {
			for(int j=1;j<9;j++) {//乘号位置
				int num1 = 0;
				int num2 = 0;
				for(int h=0;h<j;h++) {//乘号左边数值
						num1=num1*10+num[i][h];
				}
				for(int h=j;h<9;h++) {//乘号右边数值
						num2=num2*10+num[i][h];
				}
				int p[] = new int[10];
				Integer result = num1*num2;
				//它们的乘积也只包含1~9这9个数字,而且每个数字只出现1次
				//所以乘积长度一定是9
				if(result.toString().length()!=9)
					continue;
				Integer t = result;
				int flag=0;
				while(t!=0) {
					int a=(int) (t%10);//取每一位数值
					if(a==0) { //乘积只包含1~9,所以不可能含0
						flag=1;
						break;
					}
					p[a]++;
					if(p[a]!=1) { //每个数字只能出现一次
						flag=1;
						break;
					}
					t=t/10;
				}
				if(flag==0)
					max=max>result?max:result; //用符合结果的乘积更新max值
			}
		}
		System.out.println(max);
	}

}
    

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值