算法研究,应付考试

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;http://www.huiyi8.com/gundongdaima/
String[] numbers = test.split(" ");图片滚动代码  
for(int j = 0;j<numbers.length;j++){
if(numbers[j].startsWith("+")){
numbers[j]= numbers[j].substring(1);
if(sum==110){
return true;
return false;

posted @ 2014-07-29 14:06  回车桌面  阅读(137)  评论(0编辑  收藏  举报