123456789=100,表达式左边使用任意多个+号与-号,使等式成立

说明:

1到9之间共有8个位置可以做为插入点,每个点有三种插入方式:+号,-号,不插入

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created by zhangdekun on 15-5-11-下午2:37.
 */
public class TestMain {
    public static void main(String[] args) {
        System.out.println("running ....");
       rnwrap(100);
    }
    public static  Stack<String> rn(int n){
        Stack<String> stack = new Stack<>();
        Stack<String> news = new Stack<>();
        for (int i = 9; i >= 1; i--) {
            stack.add(i+"");
            if(i!=1){
                stack.add("");
            }
        }
        for(int i=0;i<8;i++){
            String c1 = stack.pop();
            String opt = stack.pop();
            String c2 = stack.pop();
            if(n%3==0){
                Integer temp = Integer.valueOf(c1)*10+Integer.valueOf(c2);
                stack.push(temp.toString());
            }else {
                news.push(c1);
                if(n%3==1){
                    news.push("+");
                }else {
                    news.push("-");
                }
                stack.push(c2);
            }
            n = n/3;
        }
        if(!stack.isEmpty()){
            news.push(stack.pop());
        }
        return news;
    }
    public static List<String> rnwrap(int total){
        List<String> result = new ArrayList<String>();
        for(int i=0;i<Math.pow(3,8);i++){
            Stack<String> st =  rn(i);
            int sum = 0;
            int opt=0;

            Stack<String> nst = new Stack<>();
            while (!st.isEmpty()){
                nst.push(st.pop());
            }
            StringBuffer sb = new StringBuffer("");
            while (!nst.isEmpty()){
                String s1 = nst.pop();
                sb.append(s1);
                if(s1.equals("+")){
                    opt =1;
                }else if(s1.equals("-")){
                    opt=2;
                }else {
                    if(opt==1){
                        sum = sum +Integer.valueOf(s1);
                    }else if(opt==2){
                        sum = sum -Integer.valueOf(s1);
                    }else {
                        sum = sum +Integer.valueOf(s1);
                    }
                    opt=0;
                }
            }
            if(sum ==total){
                System.out.println(sb);
            }
        }
        return result;
    }
}
运行结果如下:

123-45-67+89
12-3-4+5-6+7+89
12+3+4+5-6-7+89
123+4-5+67-89
1+2+3-4+5+6+78+9
12+3-4+5+67+8+9
1+23-4+56+7+8+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
123+45-67+8-9
123-4-5-6-7+8-9

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值