欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

算法研究,应付考试,算法应付考试,2012年蓝桥杯本科的第

来源: javaer 分享于  点击 21881 次 点评:75

算法研究,应付考试,算法应付考试,2012年蓝桥杯本科的第


2012年蓝桥杯本科的第九题

package liu.jyc;public class Question {    public static void main(String[] args) {        fun();        }    public static void fun(){        String[] a = new String[17]; ///        for(int i = 1;i<=9;i++){            a[2*(i-1)]=i+"";        }        for(int j = 0;j<Math.pow(3, 8);j++){///  一共有3^8种情况            int p = j;            for(int i = 0;i<8;i++){  //   一共有8个空是填运算符的                int k = p%3;//取末位 (说的是3进制的末位)                p/=3; //   精妙之处!!  去掉3进制最后一位,当下次循环就p%3就取到的是倒数第2位的数字了  我想好久才明白的                switch(k){                case 0:                    a[2*i+1]=" +";                    break;                case 1:                    a[2*i+1]=" -";                    break;                case 2:                    a[2*i+1]="o";//  代表空                    break;                }            }            //  至此,将数组转换成字符串            String test = "";            for(int i = 0;i<a.length;i++){                if(!a[i].equals("o")){ ///  是不是空 就拼成字符串                    test= test+a[i];                    }            }            if(check(test)){                System.out.println(test.replaceAll(" ", "")+"=110");            }        }    }    /**     * 判断字符串  test  是否满足题干要求   类似于   123 -4 -56 +789     * @param a     * @return     */    private static boolean check(String test) {        //  test  是这样的字符串  123 -4 -56 +789        int sum = 0;            String[] numbers = test.split(" ");            for(int j = 0;j<numbers.length;j++){                if(numbers[j].startsWith("+")){                    numbers[j]= numbers[j].substring(1);                }                sum = sum + new Integer(numbers[j]).intValue();            }        if(sum==110){            return true;        }        return false;    }}//该片段来自于http://byrx.net
相关栏目:

用户点评