您的位置:首页 > 其它

【蓝桥杯】【神奇算式】

2016-01-05 10:46 218 查看
标题:神奇算式

由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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: