Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public int calculate(String s) {
- if (s == null || s.length() == 0) {
- throw new IllegalArgumentException("Invalid input");
- }
- int i = 0;
- Stack<Integer> operands = new Stack<>();
- Stack<Character> operators = new Stack<>();
- StringBuilder number = new StringBuilder();
- while (i < s.length()) {
- char c = s.charAt(i);
- if (c == ' ') {
- i++;
- continue;
- }
- if (Character.isDigit(c)) {
- number.append(c);
- } else if (c == '(') {
- operators.push(c);
- } else if (c == ')') {
- // push the current number to the operands stack
- if (number.length() != 0) {
- operands.push(Integer.parseInt(number.toString()));
- number = new StringBuilder();
- }
- if (!operators.isEmpty() && operators.peek() != '(') {
- char op = operators.pop();
- operands.push(this.calculateValue(operands, op));
- }
- if (!operators.isEmpty()) { // pop the left bracket
- operators.pop();
- }
- } else if (c == '+' || c == '-') {
- if (number.length() != 0) {
- operands.push(Integer.parseInt(number.toString()));
- number = new StringBuilder();
- }
- if (!operators.isEmpty() && operators.peek() != '(') {
- operands.push(this.calculateValue(operands, operators.pop()));
- }
- operators.push(c);
- }
- i++;
- }
- if (number.length() != 0) {
- operands.push(Integer.parseInt(number.toString()));
- }
- // need this for the 1+1 case, don't need a while since we are only one step away
- if (!operators.isEmpty()) {
- operands.push(this.calculateValue(operands, operators.pop()));
- }
- return operands.pop();
- }
- private int calculateValue(Stack<Integer> operands, char operator) {
- // Pay attention to the stack order
- int o2 = operands.pop();
- int o1 = operands.pop();
- if (operator == '+') {
- return o1 + o2;
- } else if (operator == '-') {
- return o1 - o2;
- } else {
- throw new IllegalArgumentException("invalid operator!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement