// CodeEval Prefix expressions
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
class Main {
public static void main(String[] args) {
prefix.main(args);
}
}
class prefix {
public static void main(String[] args) {
boolean LOCAL_TEST = false;
// LOCAL_TEST = true;// comment it before submitting
if (LOCAL_TEST)
CodeEvalGetInput("e:\\zin.txt");
else
CodeEvalGetInput(args[0]);
}
public static void CodeEvalGetInput(String arg) {
try {
File file = new File(arg);
BufferedReader in = new BufferedReader(new FileReader(file));
Initialize();
String line;
while ((line = in.readLine()) != null) {
String[] lineArray = line.split("\\s");
if (lineArray.length > 0) {
// Process line of input Here
Process(lineArray);
}
}
} catch (IOException e) {
System.out.println("File Read Error: " + e.getMessage());
}
}
private static void Initialize() {
}
private static void Process(String[] lineArray) {
Stack<String> stk = new Stack<String>();
for (int i = 0; i < lineArray.length; i++) {
String s = lineArray[i];
if (IsOperator(s))
stk.push(s);
else {
if (IsOperator(stk.peek())) {
stk.push(s);
} else {
double operand1 = Double.valueOf(stk.pop());
double operand2 = Double.valueOf(s);
String operator = stk.pop();
double result = 0;
if (operator.equals("+"))
result = operand1 + operand2;
if (operator.equals("*"))
result = operand1 * operand2;
if (operator.equals("/"))
result = operand1 / operand2;
stk.push(String.valueOf(result));
}
}
}
System.out.println(Double.valueOf(stk.pop()).intValue());
}
static boolean IsOperator(String s) {
return ("+*/".contains(s));
}
}
No comments:
Post a Comment