---
title: "四则混合运算，java实现"
author: "kevin_in_java"
date: "2012-03-01T14:15:39Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-03-01T14:15:39Z"
id: 1434301
url: "https://kevin-in-java.iteye.com/blog/1434301"
---

```
package com.interview.prepare;
/*
 * 四则运算，没有括号，数字均小于零，其中中间运算过程取整。
 * 首先将运算时转换为逆波兰式（后缀式）
 * 然后通过一个栈辅助运算。当信息为数字时入栈，当信息为符号时~（~代表+-* /
 * 一种），出栈并
 * 做运算top2~top1
 * 测试用例   3+8*2/9-2 结果输出2
 * 
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Compute {
	public static void main(String args[]){
		String str = "3+8*2/9-2";
		System.out.println(getRes(str));
	}
	
	
	
	
	public static int getRes(String str){
		char[] array = str.toCharArray();
		List<Character> output = new ArrayList<Character>();;
		Stack<Character> sign = new Stack<Character>(); 
		for(int i=0;i<array.length;i++)
		{
			if(array[i]>'0'&&array[i]<='9'){
				output.add(array[i]);
			}
			else if(sign.empty()||getBoolean(sign,array[i]))
			{
				sign.push(array[i]);
			}
			else{
				while(!sign.empty()&&!getBoolean(sign, array[i]))
					output.add(sign.pop());
				sign.push(array[i]);
			}
		}
		while(!sign.empty())
		{
			output.add(sign.pop());
		}
		System.out.println(output);
		Stack<Integer> res =  new Stack<Integer>();
		Integer result = null;
		for(Character temp :output)
		{
			if(temp>'0'&&temp<='9')
			{
				res.push(temp-'0');
			}
			else {
				int top1 = res.pop();
				int top2 =res.pop();
				switch(temp){
				case '+':
					result = top2+top1;
					break;
				case '-':
					result = top2-top1;
					break;
				case '*':
					result = top2*top1;
					break;
				case '/':
					result = top2/top1;
					break;
				}
				res.push(result);
			}
		}
		return result;
	}
	private static boolean getBoolean(Stack stack,char element)
	{
		Character c = (Character)stack.peek();
		if((c=='+'||c=='-')&&(element=='*'||element=='/'))
			return true;
		return false;
	}
}
```