Skip to content

Instantly share code, notes, and snippets.

@rohan-bansal
Last active November 12, 2019 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohan-bansal/ece713f49558a5ed7475fd7e247aacd4 to your computer and use it in GitHub Desktop.
Save rohan-bansal/ece713f49558a5ed7475fd7e247aacd4 to your computer and use it in GitHub Desktop.
Calculator that converts infix to postfix, then solves.
import java.util.Stack;
import java.lang.*;
public class PostfixCalculator {
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2) {
switch (op1) {
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix) {
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++) {
c = infix.charAt(i);
if (!isOperator(c)) {
postfix.append(c + " ");
}
else {
if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop() + " ");
}
if (!stack.isEmpty()) {
stack.pop();
}
}
else {
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek())) {
stack.push(c);
}
else {
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek())) {
Character pop = stack.pop();
if (c != '(') {
postfix.append(pop + " ");
} else {
c = pop;
}
}
stack.push(c);
}
}
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop() + " ");
}
return postfix.toString();
}
public static void main(String[] args) {
// 3*2-(4+5)+1
long startTime = 0L;
long endTime = 0L;
startTime = System.nanoTime();
System.out.println(calculator(convertToPostfix(args[0]).split(" ")));
endTime = System.nanoTime();
System.out.println("Operation took " + (endTime - startTime) + " nanoseconds");
}
public static double calculator(String[] strArr) {
Stack<Double> operands = new Stack<Double>();
for(String str : strArr) {
if (str.trim().equals("")) {
continue;
}
switch (str) {
case "+":
case "-":
case "*":
case "/":
double right = operands.pop();
double left = operands.pop();
double value = 0;
switch(str) {
case "+":
value = left + right;
break;
case "-":
value = left - right;
break;
case "*":
value = left * right;
break;
case "/":
value = left / right;
break;
default:
break;
}
operands.push(value);
break;
default:
operands.push(Double.parseDouble(str));
break;
}
}
return operands.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment