Java实现第八届蓝桥杯9算数式

9算数式

题目描述
观察如下的算式:

9213 x 85674 = 789314562

左边的乘数和被乘数正好用到了1~9的所有数字,每个1次。
而乘积恰好也是用到了1~9的所有数字,并且每个1次。

请你借助计算机的强大计算能力,找出满足如上要求的9数算式一共有多少个?

注意:

  1. 总数目包含题目给出的那个示例。
  2. 乘数和被乘数交换后作为同一方案来看待。
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Scanner;

/**
 * 
 * @description TODO
 * @author frontier
 * @time 2019年3月23日 上午9:24:01
 *
 */
public class 结果填空29算数式 {
	static Scanner in = new Scanner(System.in);
	static boolean[] vis = new boolean[10];
	static int count;
	static int a, b, result;

	public static void main(String[] args) throws ParseException, FileNotFoundException {
		Scanner in = new Scanner(new File("src/JavaA/s8/1.txt"));
		dfs(0, "");
		System.out.println(count / 2);

	}

	static boolean check(int num) {
		String n = num + "";
		boolean[] v = new boolean[10];
		if (n.length() != 9)
			return false;
		for (int i = 0; i < 9; ++i) {
			int cur = Integer.parseInt(n.charAt(i) + "");
			if (cur < 1 || cur > 9)
				return false;
			if (!v[cur])
				v[cur] = true;
			else
				return false;
		}
		return true;
	}

	static boolean check1(int resultNum) {
		boolean isVisitedC[] = new boolean[10];
		while (resultNum != 0) {
			int numNow = resultNum % 10;
			if (numNow < 1 && numNow > 9)
				return false;
			isVisitedC[numNow] = true;
			resultNum /= 10;
		}
		for (int i = 1; i < 10; i++) {
			if (isVisitedC[i] == false)
				return false;
		}
		return true;
	}

	static void dfs(int n, String s) {
		if (n == 9) {
			for (int i = 1; i <= 8; ++i) {
				a = Integer.parseInt(s.substring(0, i));
				b = Integer.parseInt(s.substring(i));
				result = a * b;
				if (check(result))
					count++;
			}
			return;
		}

		for (int i = 1; i <= 9; ++i) {
			if (!vis[i]) {
				vis[i] = true;
				dfs(n + 1, s + i);
				vis[i] = false;
			}
		}
	}
}

原文地址:https://www.cnblogs.com/a1439775520/p/13077419.html