BASIC CALCULATOR STACK

mail@pastecode.io avatar
unknown
java
7 months ago
1.4 kB
0
Indexable
Never
//Q4 BASIC CALCULATOR STACK
import java.util.Scanner;
import java.util.Stack;

public class Main{
  public static int calculate(String s){
    Stack<Integer> stack = new Stack<>();
    int num = 0;
    char sign = '+';
    
    for (int i = 0; i < s.length(); i++){
      char c = s.charAt(i);
      if (Character.isDigit(c)){
        num = num * 10 + (c - '0');
      }
      if (c == '('){
        int j = i + 1;
        int count = 1;
        while (count != 0){
          if (s.charAt(j) == '(') count++;
          else if (s.charAt(j) == ')') count--;
          j++;
        }
        num = calculate(s.substring(i + 1, j - 1));
        i = j - 1;
      }
      if ((!Character.isDigit(c) && c !=' ') || i == s.length() - 1) {
        if (sign == '+'){
          stack.push(num);
        } else if (sign == '-'){
          stack.push(-num);
        } else if (sign == '*'){
          stack.push(stack.pop() * num);
        } else if (sign == '/'){
          stack.push(stack.pop() / num);
        }
        sign = c;
        num = 0;
      }
    }
    
    int result = 0;
    while (!stack.isEmpty()){
      result += stack.pop();
    }
    return result;
  }
  
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    int result = calculate(str);
    System.out.println(result);
  }
}
Leave a Comment