import java.util.List; import java.util.Stack; public class EvaluatingExpression { public static void main(String[] args) { System.out.println(evaluateExp("2+2")); System.out.println(evaluateExp("2 * ( 4 * 5 + 1 )")); } public static int evaluateExp(String expression) { char[] tokens = expression.toCharArray(); Stack<Integer> values = new Stack<Integer>(); Stack<Character> operators = new Stack<Character>(); for (int i = 0; i < tokens.length; i++) { if (tokens[i] == ' ') { continue; } if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuilder sb = new StringBuilder(); while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') { sb.append(tokens[i++]); } i--; values.push(Integer.parseInt(sb.toString())); } else if (tokens[i] == '(') { operators.push(tokens[i]); } else if (tokens[i] == ')') { while (operators.peek() != '(') { values.push(applyOperation(operators.pop(), values.pop(), values.pop())); } operators.pop(); } else if (isOperator(tokens[i])) { while (!operators.isEmpty() && hasPrecedence(tokens[i], operators.peek())) { values.push(applyOperation(operators.pop(), values.pop(), values.pop())); } operators.push(tokens[i]); } } while (!operators.isEmpty()) { values.push(applyOperation(operators.pop(), values.pop(), values.pop())); } return values.pop(); } private static boolean hasPrecedence(char op1, char op2) { if (op2 == '(' || op1 == ')') { return false; } if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) { return false; } return true; } private static boolean isOperator(char ch) { return List.of('+', '*', '-', '/').contains(ch); } private static Integer applyOperation(Character ope, Integer a, Integer b) { return switch (ope) { case '+' -> a + b; case '-' -> a - b; case '*' -> a * b; case '/' -> { if (b == 0) throw new IllegalArgumentException("Unsupported exception"); yield a / b; } default -> throw new IllegalArgumentException("Unknown operator"); }; } }
Monday, December 5, 2022
Expression Evaluating - Using Java Stack
Subscribe to:
Post Comments (Atom)
Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers
pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0...
-
Installation of MongoDB The executable file needs to be downloaded from: https://www.mongodb.com/download-center?jmp=nav#communit...
-
Form to add multiple rows: <! DOCTYPE html> <%@ page language = "java" contentType = "text/html; cha...
No comments:
Post a Comment