24点计算


package org.qinghua.dispatcher.test;

import java.util.Stack;

public class Gift {
static String[] oprs = { "+", "-", "*", "/" };
static Stack<Integer> numStack = new Stack<Integer>();
static Stack<String> oprStack = new Stack<String>();

public static void main(String[] args) {
int num = 0;
for (int i = 1; i < 10; i++) {
for (int x = 0; x < 4; x++) {
for (int j = 1; j < 10; j++) {
for (int y = 0; y < 4; y++) {
for (int m = 1; m < 10; m++) {
for (int z = 0; z < 4; z++) {
for (int n = 1 ; n < 10; n++) {
numStack.push(i);
numStack.push(j);
numStack.push(m);
numStack.push(n);
oprStack.push(oprs[x]);
oprStack.push(oprs[y]);
oprStack.push(oprs[z]);
// printStack(numStack);
// System.out.print(",");
// printStack(oprStack);
if (cal24(numStack, oprStack)) {
//printStack(numStack);
//System.out.print(",");
///printStack(oprStack);
//;
System.out.print(
new StringBuffer(i+oprs[x]+j+oprs[y]+m+oprs[z]+n).reverse().toString()+" = 24 "
+(++num)+"\n");
}
// System.out.print(i+oprs[x]+j+oprs[y]+m+oprs[u]+n+"
// ");

}
}
}
}
}
}
}
System.out.println("Number : " + num);
}

static void printStack(Stack stack) {
System.out.print(stack);
stack.clear();
}

static boolean cal24(Stack<Integer> ints, Stack<String> oprs) {
int r = 0;
while (!oprs.empty()) {
String opr = oprs.pop();
int a = ints.pop();
int b = ints.pop();
r = oprtwo(opr, a, b);
ints.push(r);
if (r == 0) {
ints.clear();
oprs.clear();
return false;
}

}

if ((r = ints.pop()) == 24) {
ints.clear();
oprs.clear();
return true;
}
return false;
}

static int oprtwo(String opr, int a, int b) {
if (opr.equals("+"))
return a + b;
if (opr.equals("-"))
return a - b<0?0:a-b;
if (opr.equals("*"))
return a * b;
if (opr.equals("/") && b != 0 && a > b && isIntegerRst(a, b)) {
return a / b;
} else
return 0;
}

static boolean gyouxian(String opr1, String opr2) {
if (opr1.equals(opr2))
return false;
if (opr1.equals("+") && (opr2.equals("/") || opr2.equals("*")))
return false;
if (opr1.equals("-") && (opr2.equals("/") || opr2.equals("*")))
return false;
return true;

}

static boolean isIntegerRst(int ai, int bi) {
Integer a = ai;
Integer b = bi;
Float an = Float.valueOf(a.toString());
Float bn = Float.valueOf(b.toString());
//System.out.println(an/bn);
return (String.valueOf((an / bn)).endsWith(".0"));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值