标题:9数算式
观察如下的算式:
9213 x 85674 = 789314562
左边的乘数和被乘数正好用到了1~9的所有数字,每个1次。
而乘积恰好也是用到了1~9的所有数字,并且每个1次。
请你借助计算机的强大计算能力,找出满足如上要求的9数算式一共有多少个?
注意:
1. 总数目包含题目给出的那个示例。
2. 乘数和被乘数交换后作为同一方案来看待。
1625
解析:要关注题目提醒的部分,可能涉及到重复情况的排查。这个题目要注意最后除以2。基本思路就是回溯,check()
import java.util.HashSet;
import java.util.Set;public class Main
{static Set<Integer> set = new HashSet<Integer>();static int[] a = new int[10];static boolean[] b = new boolean[10];static int cnt = 0;public static void main(String[] args) {f(1);System.out.println(cnt/2);}private static void f(int m) {// TODO Auto-generated method stubif (m == 10) {if (check()) {return;}}for (int i = 1; i < 10; i++) {if (b[i] == false) {b[i] = true;a[i] = m;f(m+1);b[i] = false;}}}private static boolean check() {// TODO Auto-generated method stubint[] x = new int[9];x[1] = a[9] + a[8]*10 + a[7]*100 + a[6]*1000 + a[5]*10000 + a[4]*100000 + a[3]*1000000 + a[2]*10000000;x[2] = a[9] + a[8]*10 + a[7]*100 + a[6]*1000 + a[5]*10000 + a[4]*100000 + a[3]*1000000;x[3] = a[9] + a[8]*10 + a[7]*100 + a[6]*1000 + a[5]*10000 + a[4]*100000;x[4] = a[9] + a[8]*10 + a[7]*100 + a[6]*1000 + a[5]*10000;x[5] = a[9] + a[8]*10 + a[7]*100 + a[6]*1000;x[6] = a[9] + a[8]*10 + a[7]*100;x[7] = a[9] + a[8]*10;x[8] = a[9];int[] y = new int[9];y[1] = a[1];y[2] = a[2] + a[1]*10;y[3] = a[3] + a[2]*10 + a[1]*100;y[4] = a[4] + a[3]*10 + a[2]*100 + a[1]*1000;y[5] = a[5] + a[4]*10 + a[3]*100 + a[2]*1000 + a[1]*10000;y[6] = a[6] + a[5]*10 + a[4]*100 + a[3]*1000 + a[2]*10000 + a[1]*100000;y[7] = a[7] + a[6]*10 + a[5]*100 + a[4]*1000 + a[3]*10000 + a[2]*100000 + a[1]*1000000;y[8] = a[8] + a[7]*10 + a[6]*100 + a[5]*1000 + a[4]*10000 + a[3]*100000 + a[2]*1000000 + a[1]*10000000;int[] sum = new int[9];sum[1] = x[1] * y[1];sum[2] = x[2] * y[2];sum[3] = x[3] * y[3];sum[4] = x[4] * y[4];sum[5] = x[5] * y[5];sum[6] = x[6] * y[6];sum[7] = x[7] * y[7];sum[8] = x[8] * y[8];int s = get(sum);if (s != 0) {System.out.println(sum[s]);return true;}return false;}// 查找一组sum中有多少符合的情况,注意有可能一组sum多个符合的情况private static int get(int[] sum) {// TODO Auto-generated method stubint s = 0;for (int i = 1; i < 9; i++) {set.clear();s += hx(sum[i]);}if (s != 0) {cnt+=s;return s;}return 0;}// 将sum[i] 存入 set中,如果个数符合则证明找到一个private static int hx(int x) {// TODO Auto-generated method stubwhile(x != 0) {set.add(x%10);x/=10;}if (set.size() == 9 && !set.contains(0)) {return 1;}return 0;}
}