1. 简单枚举
输入正整数n,按从小到大的顺序输出所有形如abcde/fghij= n的表达式,其中a~j恰好为数字0~9的一个排列(可以有前导0),2≤n≤79。
输入
62
输出
79546 / 01283 = 62
94736 / 01528 = 62
代码
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
//文件名:Main.java
public class Main
{
static int n;
static Set<Integer> set = new HashSet<>();// 用于数字去重
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 1234; i < 100000; i++)
{
if (repeat(i))
continue;
int y = cal(i);
if (y != -1)
{
System.out.print(y + "/");
System.out.printf("%05d", i);
System.out.println(" = " + n);
}
set.clear();
}
}
//返回 x 对应的 x*n,非法值则返回 -1
private static int cal(int x)
{
int y = x * n;
if (value(y))
return y;
return -1;
}
//返回 y 是否为有效值
private static boolean value(int y)
{
if (y < 10000 || y >= 100000)
return false;
Set<Integer> tmpSet = new HashSet<>();
while (y != 0)
{
int t = y % 10;
if (tmpSet.contains(t) || set.contains(t))
return false;
tmpSet.add(t);
y /= 10;
}
return true;
}
//返回 x 的每一位是否有重复的数字,有则返回 true
private static boolean repeat(int x)
{
if ((x + "").length() == 4)
x *= 10;
while (x != 0)
{
int t = x % 10;
if (set.contains(t))
{
set.clear();
return true;
}
set.add(t);
x /= 10;
}
return false;
}
}
2. 猜数字
46*79=23*158
要求找出所有的乘法等式,并1-9个数字只能用一次。没懂😴
代码
🔔 更正:没有 0
// 文件名:Main.java
import java.util.*;
public class Main
{
static Set<Character> set = new HashSet<>();
public static void main(String[] args)
{
dfs("");
}
private static void dfs(String s)
{
if (s.length() == 9)
{
print(s);
return;
}
// for (char c = '0'; c <= '9'; c++)
for (char c = '1'; c <= '9'; c++)// 更正不能为 0
{
if (set.contains(c))
continue;
set.add(c);
dfs(s + c);
set.remove(c);
}
}
private static void print(String s)
{
int a = Integer.valueOf(s.substring(0, 2));
int b = Integer.valueOf(s.substring(2, 4));
int c = Integer.valueOf(s.substring(4, 6));
int d = Integer.valueOf(s.substring(6, 9));
if (s.charAt(0) == '0' || s.charAt(2) == '0' || s.charAt(4) == '0' || s.charAt(6) == '0')
return;
if (a * b == c * d)
System.out.println(a + " * " + b + " = " + c + " * " + d);
}
}
输出结果
46 * 79 = 23 * 158
54 * 69 = 27 * 138
54 * 93 = 27 * 186
58 * 67 = 29 * 134
58 * 69 = 23 * 174
58 * 73 = 29 * 146
58 * 96 = 32 * 174
63 * 74 = 18 * 259
64 * 79 = 32 * 158
67 * 58 = 29 * 134
69 * 54 = 27 * 138
69 * 58 = 23 * 174
73 * 58 = 29 * 146
73 * 96 = 12 * 584
74 * 63 = 18 * 259
76 * 98 = 14 * 532
79 * 46 = 23 * 158
79 * 64 = 32 * 158
93 * 54 = 27 * 186
96 * 58 = 32 * 174
96 * 73 = 12 * 584
98 * 76 = 14 * 532