逆波兰表达式的面试应用

写一个方法,参数传递一个字符串表达式,返回结果为表达式计算结果。如:传递表达式"1+2*3+6-2/2"返回计算的结果。

 

自己粗写了一个,也算是学习了一下,没有做字符串的初始化和加入全部运算符,但是要用的人改改容易完善

package com.ll.test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.StringTokenizer;
/**
 * 
 * @author LiuLiu
 *
 */
public class CalculateString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AnalyzingExpression ae = new AnalyzingExpression(
				"4-(4-3*5+(2*4)+100)/10");
		ae.toRight();
		ae.getResult();
	}

}

class AnalyzingExpression {
	private String e = "4-(4-3*5+(2*4)+100)/10";
	private ArrayList<String> ori = new ArrayList<String>();
	private ArrayList<String> right = new ArrayList<String>();
	private String result;

	public ArrayList<String> getRight() {
		return right;
	}

	public AnalyzingExpression(String input) {
		StringTokenizer st = new StringTokenizer(input.replaceAll(" ", ""),
				"+-*/()", true);
		while (st.hasMoreElements()) {
			ori.add(st.nextToken());
		}
	}

	public void toRight() {
		Stack<String> s = new Stack<String>();// 运算符栈
		int position = 0;
		while (true) {
			String currentOriEle = ori.get(position);
			if (Calculate.isOperator(currentOriEle)) {// 如果是运算符需要处理
				if (s.empty() || currentOriEle.equals("(")) {// 如果是空栈,或者是"("直接入栈
					s.push(currentOriEle);
				} else if (currentOriEle.equals(")")) {// 若为')',出栈并顺序输出运算符直到遇到第一个'(',遇到的第一个'('出栈但不输出;
					while (!s.empty()) {
						if (s.peek().equals("(")) {
							s.pop();
							break;
						} else {
							right.add(s.pop());
						}
					}
				} else {// 若为其它,比较stackOperator栈顶元素与当前元素的优先级:如果栈顶元素是'(',当前元素入栈;如果栈顶元素
					// >= 当前元素,出栈并顺序输出运算符直到 栈顶元素 < 当前元素,然后当前元素入栈; 如果 栈顶元素 <
					// 当前元素,直接入栈。
					if (s.peek().equals("(")) {
						s.push(currentOriEle);
					} else {
						while (!s.empty()
								&& Calculate.priority(currentOriEle) <= Calculate
										.priority(s.peek())) {
							right.add(s.pop());
						}
						s.push(currentOriEle);
					}
				}
			} else {// 数字直接进list
				right.add(currentOriEle);
			}
			position++;
			if (position >= ori.size())
				break;
		}
		while (!s.empty()) {// 运算符栈不为空入list
			right.add(s.pop());
		}
	}

	// 对右序表达式进行求值
	public void getResult() {
		Stack<Double> s = new Stack<Double>();
		double n1 = 0;
		double n2 = 0;
		String e = null;
		Iterator<String> it = right.iterator();

		while (it.hasNext()) {
			e = it.next();
			if (Calculate.isOperator(e)) {
				n1 = s.pop();
				n2 = s.pop();
				s.push(Calculate.twoResult(e, n1, n2));
			} else
				s.push(Double.parseDouble(e));
		}
		result = String.valueOf(s.pop());
		it = right.iterator();
		while (it.hasNext()) {
			System.out.print(it.next());
		}
		System.out.println("=" + result);
	}
}

class Calculate {
	public static boolean isOperator(String operator) {
		if ("+-*/()".contains(operator)) {
			return true;
		} else {
			return false;
		}
	}

	public static int priority(String operator) {
		if ("+-".contains(operator))
			return 3;
		else if ("(".contains(operator))
			return 1;
		else if ("*/".contains(operator))
			return 5;
		else
			return 0;
	}

	public static double twoResult(String operator, double y, double x) {
		try {
			double z = 0;
			if (operator.equals("+"))
				z = x + y;
			else if (operator.equals("-"))
				z = x - y;
			else if (operator.equals("*"))
				z = x * y;
			else if (operator.equals("/"))
				z = x / y;
			else
				z = 0;
			return z;
		} catch (NumberFormatException e) {
			throw e;
		}
	}
}

class Stack<T> {
	private LinkedList<T> ll = new LinkedList<T>();

	public void push(T e) {
		ll.addFirst(e);
	}

	public T pop() {
		return ll.removeFirst();
	}

	public T peek() {
		return ll.getFirst();
	}

	public boolean empty() {
		return ll.isEmpty();
	}
}

你可能感兴趣的:(面试)