现有n根火柴,希望拼出式子:A+B=C。等式中的A、B、C都是火柴棍拼出来的整数。
数字0~9如图:
注意:1、加号和等号各需要两根火柴
2、如果A不等于B,则A+B=C和B+A=C视为不同的等式
3、A、B、C均大于0
4、火柴必须全部用上,不能多,也不能少
5、A、B的最高位都不能为0 (A=0和B=0除外)
一、初始版本(漏洞很多)
这个只能测试A、B、C均为两位数以内的-_-!
public class Test {
static int num;
static int[] hc = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
public static void main(String[] args) {
Scanner out = new Scanner(System.in);
try {
System.out.print("有几根火柴:");
num = out.nextInt() - 4;
int c;
D: for (int a = 0; a < 50; a++) {
for (int b = 0; b < 50; b++) {
c = a + b;
if (a > 9 || b > 9 || c > 9) {
int ha = 0;
int hb = 0;
if (a > 9) {
int x, y;
x = a / 10;
y = a % 10;
ha = hc[x] + hc[y];
} else {
ha = hc[a];
}
if (b > 9) {
int x, y;
x = b / 10;
y = b % 10;
hb = hc[x] + hc[y];
} else {
hb = hc[b];
}
int x, y;
x = c / 10;
y = c % 10;
if (ha + hb + hc[x] + hc[y] == num) {
System.out.println(a + "+" + b + "=" + c);
}
} else {
if (hc[a] + hc[b] + hc[c] == num) {
System.out.println(a + "+" + b + "=" + c);
}
}
}
}
} finally {
out.close();
}
}
}
二、经参考修改后的版本
我是参考了《啊哈算法》中的C语言,自己转成Java。
精髓在于cal方法里对非个位数的分解
public class Test {
static int num;
static int[] hc = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
static int haha = 0;// 统计有多少种摆法
public static int cal(int x) {
int n = 0;
while (x / 10 != 0) {
n += hc[x % 10];
x = x / 10;
}
n += hc[x];
return n;
}
public static void main(String[] args) {
Scanner out = new Scanner(System.in);
try {
System.out.print("有几根火柴:");
num = out.nextInt() - 4;
for (int a = 0; a < 1111; a++) {
for (int b = 0; b < 1111; b++) {
int c = a + b;
if (cal(a) + cal(b) + cal(c) == num) {
System.out.println(a + "+" + b + "=" + c);
haha++;
}
}
}
System.out.println("一共有" + haha + "种摆法");
} finally {
out.close();
}
}
}