Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.PriorityQueue;
- import java.util.Stack;
- public class ExpressionEvaluator {
- public static int evaluate(int a, char sign, int b) {
- if (sign == '+') return a + b;
- else if (sign == '*') return a * b;
- return 0;
- }
- public static int evaluateExpression(String expression) {
- char symbols[] = expression.toCharArray();
- Stack<Character> charStack = new Stack<>();
- Stack<Integer> intStack = new Stack<>();
- for (int i = 0; i < symbols.length; i++) {
- if (symbols[i] == '+' || symbols[i] == '*') {
- charStack.push(symbols[i]);
- } else {
- intStack.push(symbols[i] - '0');
- }
- }
- /*System.out.println(intStack.toString());
- System.out.println(charStack.toString());
- System.out.println();*/
- charStack = new Stack<>();
- intStack = new Stack<>();
- StringBuilder sb = new StringBuilder();
- for (int i=0 ; i<expression.length(); ++i) {
- char curr = expression.charAt(i);
- if ( curr == '+' || curr =='*') {
- intStack.push(Integer.parseInt(sb.toString()));
- sb = new StringBuilder();
- charStack.push(curr);
- }
- else {
- sb.append(curr);
- }
- }
- intStack.push(Integer.parseInt(sb.toString()));
- /*System.out.println(intStack.toString());
- System.out.println(charStack.toString());*/
- while (!charStack.isEmpty()) {
- int a = intStack.pop();
- int b = intStack.pop();
- char sign = charStack.pop();
- if (sign == '*') {
- intStack.push(a * b);
- } else {
- if (charStack.isEmpty() || charStack.peek() == '+') {
- intStack.push(a + b);
- } else {
- /* a & b want to add, but b must multiply first */
- int temp = intStack.pop(); /* get next int */
- charStack.pop(); /* another multiplication, just get rid of it */
- intStack.push(b * temp); /* second * third */
- intStack.push(a); /* add a on top after b is done */
- charStack.push(sign); /* preserve the + we got at the start */
- }
- }
- }
- return intStack.pop();
- }
- public static void main(String[] args) throws IOException {
- BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
- System.out.println(evaluateExpression(input.readLine()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment