论坛首页 招聘求职论坛

深圳两个上机题,求讨论!

浏览 31629 次
精华帖 (0) :: 良好帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-04-21  
import java.util.Stack;

public class Polish{
	public static void main(String[] args){
		String ex1= "2+3*5+(4*5-6)/2";
		Polish p = new Polish();
		String c = p.createPolish(ex1);
		System.out.println(c);
		System.out.println(p.parsePolish(c));
	}
	public int parsePolish(String ex){
		String exs[] = ex.split(" ");
		Stack s = new Stack();
		for(int i=0;i<exs.length;i++){
			if(exs[i].equals("+")){
				s.push(Integer.parseInt(s.pop().toString())
						+ Integer.parseInt(s.pop().toString()));
			}else if(exs[i].equals("-")){
				s.push(-Integer.parseInt(s.pop().toString())
						+ Integer.parseInt(s.pop().toString()));
			}else if(exs[i].equals("*")){
				s.push(Integer.parseInt(s.pop().toString())
						* Integer.parseInt(s.pop().toString()));
			}else if(exs[i].equals("/")){
				int divider = Integer.parseInt(s.pop().toString());
				int dividend = Integer.parseInt(s.pop().toString());
				s.push(dividend/divider);
			}else
				s.push(exs[i]);
		}
		return Integer.parseInt(s.pop().toString());
	}
	public String createPolish(String ex1){
		ex1 = express(ex1);
		String exs1[] = ex1.split(" ");
		Stack s = new Stack();
		StringBuffer polishEx = new StringBuffer();
		int flag = 0;
		for(int i=0;i<exs1.length;i++){
			if(exs1[i].equals("+") || exs1[i].equals("-")){
				if(flag == 2){
					while(s.size()>0){
						if(s.peek().equals("(")){
							break;
						}else{
							polishEx.append(s.pop()+ " ");
						}
					}
				}
				s.push(exs1[i]);
				flag = 1;
				
			}else if(exs1[i].equals("*") || exs1[i].equals("/")){
				s.push(exs1[i]);
				flag = 2;
			}else if(exs1[i].equals(")")){
				while(!s.peek().toString().equals("(")){
					polishEx.append(s.pop()+ " ");
				}
				s.pop();
			}else if(exs1[i].equals("(")){
				s.push(exs1[i]);
			}else{
				polishEx.append(exs1[i]+ " ");
			}
		}
		while(s.size()>0)
			polishEx.append(s.pop()+ " ");
		return polishEx.substring(0, polishEx.length()-1);
	}
	
	private String express(String o){
		return o = o.replace(" ","").replace("+", " + ").replace("-", " - ").
 		replace("*", " * ").replace("/", " / ").replace("(", "( ")
 		.replace(")", " )");
	}
}
0 请登录后投票
论坛首页 招聘求职版

跳转论坛:
Global site tag (gtag.js) - Google Analytics