蓝桥杯—最大乘积—思路清晰—步骤详细

1、问题描述

把 1~9 这9个数字分成两组,中间插入乘号,
有的时候,它们的乘积也只包含1~9这9个数字,而且每个数字只出现1次。
比如:
984672 * 351 = 345619872
98751 * 3462 = 341875962
9 * 87146325 = 784316925

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

2、代码实现

import java.util.HashSet;

public class 最大乘积 {
	static char[] arr = {'1','2','3','4','5','6','7','8','9'};
	static int max = 0;
	
	public static void main(String[] args) {
		arrange(0);
		System.out.println(max);
	}
	public static void arrange(int k) {
		if(k == 9) {
			//将数组转为对应的int类型数字
			int s = 0;
			for(int i = 0;i < 9;i++) {
				s = s * 10 + (arr[i] - 48);
			}
			//将该数字裁剪,相乘得到结果
			trim(s);
			return;
		}
		for(int i = k;i < 9;i++) {
			swap(i,k);
			arrange(k + 1);
			swap(i,k);
		}
	}
	public static void swap(int a,int b) {
		char t = arr[a];
		arr[a] = arr[b];
		arr[b] = t;
	}
	//用*分割,并把这两个数相乘
	public static void trim(int n) {
		String s = n + "";
		for(int i = 1;i < 9;i++) {
			int n1 = Integer.parseInt(s.substring(0,i));
			int n2 = Integer.parseInt(s.substring(i));
			//验算结果
			boolean flag = repeat(n1 * n2);
			if(flag) {
				max = Math.max(max, n1 * n2);
			}
		}
	}
	//是否有重复数字
	public static boolean repeat(int n) {
		HashSet<Integer> set = new HashSet<>();
		
		while(n > 0) {
			if(n % 10 == 0) {
				return false;
			}
			set.add(n % 10);
			n /= 10;
		}
		
		return set.size() == 9;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@小红花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值