神奇算式
题目
由4个不同的数字,组成的一个乘法算式,它们的乘积仍然由这4个数字组成。
比如:
210 x 6 = 1260
8 x 473 = 3784
27 x 81 = 2187
都符合要求。
如果满足乘法交换律的算式算作同一种情况,那么,包含上边已列出的3种情况,一共有多少种满足要求的算式。
思路
全排列+去重
- 首先用全排列,得到所有的0~9的前四个数字的可能。
- 然后通过Set集合将全排列中所有前四个数字的情况总顺序相同,数字也相同的可能去重掉
- 然后进入check方法进行判断,然后用四重循环得到这四个数字的所有可能四位数,然后用map记录下来,减少数字相同,但排列不同时候的重复运算
- 然后用循环得到这四个数字分成两位的各种情况进行比较
import java.util.*;
public class T3神奇算式 {
static int ans;
static int ant[] = new int[]{6,0,2,1,4,5,3,7,8,9};
static Set<String> set= new HashSet<>();
static Map<String, List<Integer>> map= new HashMap<>();
public static String numToString(int[] ant,int start,int end){
StringBuffer str = new StringBuffer("");
for(int i=start;i<end;i++){
str.append(ant[i]);
}
return str.toString();
}
private static void check() {
int a=ant[0];
int b=ant[1];
int c=ant[2];
int d=ant[3];
String s = numToString(new int[]{a,b,c,d},0,4);
List<Integer> list = new ArrayList<>();
if(map.get(s)!=null)
list=map.get(s);
else {
for (int i = 0; i < 4; i++) {
if(ant[i]==0)
continue;
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
for (int z = 0; z < 4; z++) {
if (i != j && i != k && i != z
&& j != k && j != z
&& k != z) {
int num = 0;
num = num * 10 + ant[i];
num = num * 10 + ant[j];
num = num * 10 + ant[k];
num = num * 10 + ant[z];
list.add(num);
}
}
}
}
}
for(int i : list){
map.put(String.valueOf(i),list);
}
}
int numA=0;
int numB=0;
for(int i=0;i<=2;i++){
if(ant[0]==0)
continue;
for(int j=0;j<=i;j++){
numA=numA*10+ant[j];
}
if(numA==0) {
numA=0;
continue;
}
if(ant[i+1]==0) {
numA=0;
continue;
}
for(int j=i+1;j<4;j++){
numB=numB*10+ant[j];
}
if(numB==0) {
numA=0;
numB=0;
continue;
}
for(int numC:list){
if(numA*numB==numC) {
ans++;
}
}
numA=0;
numB=0;
}
}
private static void f(int k) {
if(k==10){
String s = numToString(ant,0,4);
if(set.contains(s))
return;
set.add(s);
check();
return;
}
for(int i=k;i<10;i++){
int temp=ant[k];
ant[k]=ant[i];
ant[i]=temp;
f(k+1);
temp=ant[k];
ant[k]=ant[i];
ant[i]=temp;
}
}
public static void main(String[] args) {
f(0);
System.out.println(ans/2);
}
}