IDG | 四则运算表达式计算

分析

首先将中缀表达式转换为后缀表达式(逆波兰式),然后使用栈进行计算。

没有考虑括号、小数。

代码

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class ExpCal {
	public static double calc(String exp) {
		if (exp == null || exp.length() <= 0) {
			throw new IllegalArgumentException();
		}

		char[] c = exp.toCharArray();
		Stack<Character> s = new Stack<Character>();
		List<String> reversePolishNotation = new LinkedList<String>();
		for (int i = 0; i < c.length; ++i) {
			if (c[i] == '+' || c[i] == '-' || c[i] == '*' || c[i] == '/') {
				while (!s.isEmpty() && compOp(s.peek(), c[i]) >= 0) {
					reversePolishNotation.add(String.valueOf(s.pop()));
				}
				s.push(c[i]);
			} else {
				StringBuilder sb = new StringBuilder();
				while (i < c.length && c[i] >= '0' && c[i] <= '9') {
					sb.append(c[i++]);
				}
				reversePolishNotation.add(sb.toString());
				--i;
			}
		}
		while (!s.isEmpty()) {
			reversePolishNotation.add(String.valueOf(s.pop()));
		}

		Stack<Double> num = new Stack<Double>();
		for (String e : reversePolishNotation) {
			if (e.equals("+")) {
				num.push(num.pop() + num.pop());
			} else if (e.equals("-")) {
				double a = num.pop();
				double b = num.pop();
				num.push(b - a);
			} else if (e.equals("*")) {
				num.push(num.pop() * num.pop());
			} else if (e.equals("/")) {
				double a = num.pop();
				double b = num.pop();
				num.push(b / a);
			} else {
				num.push(Double.parseDouble(e));
			}
		}

		return num.pop();
	}

	private static int compOp(char a, char b) {
		return getPri(a) - getPri(b);
	}

	private static int getPri(char c) {
		switch (c) {
		case '+':
		case '-':
			return 1;
		case '*':
		case '/':
			return 2;
		default:
			return 0;
		}
	}

	public static void main(String[] args) {
		System.out.println(calc("4*3+2*5-8/8-2*6/3+2/1-4"));
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值