“Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, …

本文介绍了一个使用Java编写的程序,该程序能够找出所有可能的方式,在数字1到9之间插入加号、减号或什么都不插入,使得最终的数学表达式结果等于100。通过将问题转换为三进制数的遍历,程序巧妙地解决了这个数学谜题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question--

“Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, …, 9 (in this order) such that the result is always 100”

Java

public static void main(String[] args) throws IOException, ScriptException {


        String[] o = { "", "-", "+" };

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");

        int sum = 0;
        for (int i = 5; i <= combinations; i++) {
            int tmp = Integer.parseInt(Integer.toString(i, 3), 10); //translate to base 3

            String str = String.format("%08d", tmp);

            int[] p = new int[8];
            for (int j = 0; j < 8; j++) {
                p[j] = str.charAt(j) - 48;
            }

            String resultS = "1" + o[p[0]] + "2" + o[p[1]] + "3" + o[p[2]] + "4" + o[p[3]] + "5" + o[p[4]] + "6"
                    + o[p[5]] + "7" + o[p[6]] + "8" + o[p[7]] + "9";

            int result = (Integer) engine.eval(resultS);
            if (result == 100) {
                sum++;
                solutions.add(resultS);
            }
        }
        for (int i = 0; i < solutions.size(); i++) {
            System.out.print(solutions.get(i) + "\n");
        }
        System.out.print(sum);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值