| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- import java.lang.Integer;
- import java.util.Scanner;
- import java.util.Stack;
- class Main {
- public static void main(String args[]) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter Equation : ");
- String postfix = infixToPostfix(input.nextLine());
- System.out.println(solve(postfix));
- input.close();
- }
- public static int solve(String postfix) {
- Stack<Integer> ints = new Stack<>();
- for (int i = 0; i < postfix.length(); i++) {
- char x = postfix.charAt(i);
- if (x == ' ') {
- continue;
- } else if (Character.isDigit(x)) {
- String fullNumber = "";
- while (postfix.charAt(i) != ' ') {
- fullNumber += postfix.charAt(i);
- i++;
- }
- ints.push(Integer.parseInt(fullNumber));
- } else {
- int num2 = ints.pop();
- int num1 = ints.pop();
- switch (x) {
- case '/':
- ints.push(num1 / num2);
- break;
- case '*':
- ints.push(num1 * num2);
- break;
- case '+':
- ints.push(num1 + num2);
- break;
- case '-':
- ints.push(num1 - num2);
- break;
- }
- }
- }
- return ints.pop();
- }
- public static Integer calculatePrecedence(Character c) {
- if (c == '*' || c == '/') {
- return 1;
- } else {
- return 0;
- }
- }
- public static String infixToPostfix(String infix) {
- Stack<Character> stack = new Stack<>();
- String postfix = "";
- int i = 0;
- while (i < infix.length()) {
- char c = infix.charAt(i);
- if (Character.isDigit(c)) {
- String num = "";
- while (
- (i < infix.length()) && Character.isDigit(infix.charAt(i))
- ) {
- num += infix.charAt(i);
- i++;
- }
- postfix += num + " ";
- } else {
- while (
- !stack.empty() &&
- calculatePrecedence(stack.peek()) >= calculatePrecedence(c)
- ) {
- postfix += stack.pop();
- }
- stack.push(c);
- i++;
- }
- }
- while (!stack.empty()) {
- postfix += stack.pop();
- }
- return postfix;
- }
- }
|