火柴棍等式

现有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();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值