# 基本计算器

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

 

示例 1:

输入:s = "1 + 1"
输出:2

示例 2:

输入:s = " 2-1 + 2 "
输出:3

示例 3:

输入:s = "(1+(4+5+2)-3)+(6+8)"
输出:23

 

提示:

## template ```cpp #include using namespace std; class Solution { public: int calculate(string s) { stack myStack; stack myOperator; int i; for (i = 0; i < s.length(); i++) { while (i < s.length() && s[i] == ' ') i++; if (i == s.length()) break; if (s[i] == '+' || s[i] == '-' || s[i] == '(') myOperator.push(s[i]); else if (s[i] == ')') { while (myOperator.top() != '(') { int element1 = myStack.top(); myStack.pop(); int element2 = myStack.top(); myStack.pop(); char op = myOperator.top(); myOperator.pop(); if (op == '+') myStack.push(element1 + element2); else if (op == '-') myStack.push(element2 - element1); } if (!myOperator.empty()) myOperator.pop(); while (!myOperator.empty() && (myOperator.top() != '(')) { int element1 = myStack.top(); myStack.pop(); int element2 = myStack.top(); myStack.pop(); char op = myOperator.top(); myOperator.pop(); if (op == '+') myStack.push(element1 + element2); else if (op == '-') myStack.push(element2 - element1); } } else { long long int number = 0; int j = i; while (j < s.length() && (s[j] - '0' <= 9) && (s[j] - '0' >= 0)) { number = number * 10 + (s[j] - '0'); j++; } i = j - 1; myStack.push(number); while (!myOperator.empty() && (myOperator.top() != '(')) { int element1 = myStack.top(); myStack.pop(); int element2 = myStack.top(); myStack.pop(); char op = myOperator.top(); myOperator.pop(); if (op == '+') myStack.push(element1 + element2); else if (op == '-') myStack.push(element2 - element1); } } } return myStack.top(); } }; ``` ## 答案 ```cpp ``` ## 选项 ### A ```cpp ``` ### B ```cpp ``` ### C ```cpp ```