【蓝桥杯】【神奇算式】

 

题目
    由4个不同的数字,组成的一个乘法算式,它们的乘积仍然由这4个数字组成。
    比如: 

210 x 6 = 1260 
8 x 473 = 3784
27 x 81 = 2187 

    都符合要求。
    如果满足乘法交换律的算式算作同一种情况,那么,包含上边已列出的3种情况,一共有多少种满足要求的算式。

 

    请填写该数字,通过浏览器提交答案,不要填写多余内容(例如:列出所有算式)。

 

分析

这个题目关键是如何去除重复的算式,我的想法比较复杂,我设计了一个内部类,这个类代表一个算式,a和b表示左边的乘数,c表示右边的积,重写这个类的equals()方法,在这个方法中,我们将乘法交换律考虑进去,然后用ArrayList集合去装载算式类的对象,通过其contains()方法来判断有没有重复的算式。

 

源码

 

public class Test013 {

	public static void main(String[] args) {

		ArrayList<Wa> list = new ArrayList<Test013.Wa>();

		for (int i = 1; i <= 100; i++) {
			for (int j = 10; j < 1000; j++) {
				int a = i * j;
				String left = "" + i + j;
				String right = "" + a;

				if (left.length() == 4 && right.length() == 4) {
					char[] leftArray = left.toCharArray();
					char[] rightArray = right.toCharArray();
					Arrays.sort(leftArray);
					Arrays.sort(rightArray);
					if (String.valueOf(leftArray).equals(
							String.valueOf(rightArray))) {
						// 找到了一种,但是要去除重复的
						Wa wa = new Wa(i, j, a);
						if (list.contains(wa)) {
							continue;
						} else {
							list.add(wa);
						}
					}
				}
			}
		}

		System.out.println(list.size());

		for (Wa x : list) {
			System.out.println(x.a + "*" + x.b + "=" + x.c);
		}
	}

	private static class Wa {
		int a;
		int b;
		int c;

		public Wa(int a, int b, int c) {
			this.a = a;
			this.b = b;
			this.c = c;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj instanceof Wa) {
				Wa wa = (Wa) obj;
				if ((this.a == wa.a && this.b == wa.b && this.c == wa.c)
						|| (this.a == wa.b && this.b == wa.a && this.c == wa.c)) {
					return true;
				}
			}
			return false;
		}
	}

}

 

结果

15种情况满足要求

 

3*501=1503
3*510=1530
5*251=1255
6*201=1206
6*210=1260
8*473=3784
8*860=6880
9*351=3159
15*93=1395
21*60=1260
21*87=1827
27*81=2187
30*51=1530
35*41=1435
80*86=6880

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值