# 224. Basic Calculator

```java
class Solution {
    public int calculate(String s) {
        // levelResult used to store the sum in parentheses
        int levelResult=0;
        int num = 0;
        // the sign of current num (number after the non-digit character)
        int sign =1;
        // stack to store the sum (levelResult) of different parentheses level
        Deque<Integer> stack = new LinkedList<>();
        for(char c : s.toCharArray()){
            switch(c){
                case '+':
                    levelResult +=sign*num;
                    sign=1;
                    num=0;
                    break;
                case '-':
                    levelResult +=sign*num;
                    sign=-1;
                    num=0;
                    break;      
                case ' ':
                    break;
                case '(':
                    stack.push(levelResult);
                    levelResult=0;
                    stack.push(sign);
                    sign=1;
                    break;
                case ')':
                    levelResult +=num*sign;
                    levelResult = stack.pop()*levelResult+stack.pop();
                    num=0;
                    sign=1;
                    break;
                default:
                    num=c-'0'+num*10;
            }
        }
        return levelResult+num*sign;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ucan.gitbook.io/notes/stack/224.-basic-calculator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
