JAVA蓝桥杯(3)猜算式

来源:互联网 发布:淘宝如何自己刷信誉 编辑:程序博客网 时间:2024/06/16 22:56

问题描述

看下面的算式:
□□ x □□ = □□ x □□□
它表示:两个两位数相乘等于一个两位数乘以一个三位数。
如果没有限定条件,这样的例子很多。
但目前的限定是:这9个方块,表示1~9的9个数字,不包含0。
该算式中1至9的每个数字出现且只出现一次!
比如:
46 x 79 = 23 x 158
54 x 69 = 27 x 138
54 x 93 = 27 x 186
…..
请编程,输出所有可能的情况!
注意:
左边的两个乘数交换算同一方案,不要重复输出!
不同方案的输出顺序不重要

解决方法

import java.util.HashMap;import java.util.HashSet;import java.util.Vector;public class Question3 {    private static HashMap<String, StringBuffer> map = new HashMap<String, StringBuffer>();    private static HashSet<String> set = new HashSet<String>();    public static void main(String[] args) {        Vector<Integer> source = new Vector<Integer>();        for (int i = 1; i <= 9; i++) {// 构造初始数据            source.add(i);        }        Vector<Integer> result = new Vector<Integer>();        new Question3().prem(source, result);// 递归        for (String key : map.keySet()) {// 输出结果            System.out.println(map.get(key).substring(0, 2) + " x " + map.get(key).substring(0, 2) + " = "                    + map.get(key).substring(0, 2) + " x " + map.get(key).substring(0, 2));        }    }    // 递归实现全排列    private void prem(Vector<Integer> source, Vector<Integer> result) {        if (source.size() == 0) {            StringBuffer stringBuffer = new StringBuffer();            for (int i = 0; i < result.size(); i++) {                stringBuffer.append(result.elementAt(i));            }            int a = Integer.parseInt(stringBuffer.substring(0, 2)) * Integer.parseInt(stringBuffer.substring(2, 4));            int b = Integer.parseInt(stringBuffer.substring(4, 6)) * Integer.parseInt(stringBuffer.substring(6, 9));            if (a == b) {                String tmp = new StringBuffer(stringBuffer.substring(2, 4)).append(stringBuffer.substring(0, 2))                        .toString();// 正常前四位                String tmpresv = new StringBuffer(stringBuffer.substring(0, 2)).append(stringBuffer.substring(2, 4))                        .toString();// 翻转后的前四位                if (set.add(tmp) && set.add(tmpresv)) {// 去除前四位重复的值,利用HashSet的值唯一特点                    map.put(tmp, stringBuffer);                }            }        }        for (int i = 0; i < source.size(); i++) {            Vector<Integer> tsource = new Vector<Integer>(source);            Vector<Integer> tresult = new Vector<Integer>(result);            tresult.add(source.elementAt(i));            tsource.remove(i);            new Question3().prem(tsource, tresult);        }    }}

运行结果

54 x 54 = 54 x 5463 x 63 = 63 x 6373 x 73 = 73 x 7376 x 76 = 76 x 7658 x 58 = 58 x 5864 x 64 = 64 x 6458 x 58 = 58 x 5854 x 54 = 54 x 5446 x 46 = 46 x 4658 x 58 = 58 x 5858 x 58 = 58 x 58
0 0
原创粉丝点击