注意:此程式用Java SE7去寫,如果是用SE6以下去編譯,switch部分會編譯錯誤
import java.util.*;
public class FiveOperations{
public static int priority(String str){
switch( str ){
case "+": case "-":
return 1;
case "*": case"/": case "%":
return 2;
default:
return 0;
}
}
public static int count(String op, int a, int b){
switch( op ){
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b;
case "%": return a % b;
default: throw new ArithmeticException(op + " not defined");
}
}
public static String toPostfix(String str){
StringBuffer sb = new StringBuffer();
LinkedList<String> stack = new LinkedList<String>();
for(String sub : str.split(" ") ){
if("(".indexOf(sub) != -1){
stack.add(sub);
}else if("+-*/%".indexOf(sub) != -1){
while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
sb.append(stack.removeLast() + " ");
}
stack.add(sub);
}else if(")".indexOf(sub) != -1){
while( "(".indexOf(stack.getLast()) == -1 ){
sb.append(stack.removeLast() + " ");
}
stack.removeLast();
}else{
sb.append(sub + " ");
}
}
while(!stack.isEmpty()){ sb.append(stack.removeLast() + " "); }
return sb.toString();
}
public static int answer(String str){
Stack<Integer> stack = new Stack<Integer>();
for(String sub : toPostfix(str).split(" ")){
if("+-*/%".indexOf(sub) != -1){
int b = stack.pop();
int a = stack.pop();
stack.push(count(sub, a, b));
}else{
stack.push(Integer.parseInt(String.valueOf(sub)));
}
}
return stack.pop();
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
System.out.println( answer(str) );
}
}
}
沒有留言:
張貼留言