class Solution {
public:
void compute(std::stack<unsigned int> &number_stack,
std::stack<char> &operation_stack){
if (number_stack.size() < 2){
return;
}
unsigned int num2 = number_stack.top();
number_stack.pop();
unsigned int num1 = number_stack.top();
number_stack.pop();
if (operation_stack.top() == '+'){
number_stack.push(num1 + num2);
}
else if(operation_stack.top() == '-'){
number_stack.push(num1 - num2);
}
operation_stack.pop();
}
int calculate(string s) {
enum state{STATE_BEGIN, NUMBER_STATE, OPERATION_STATE}STATE = STATE_BEGIN;
std::stack<unsigned int> number_stack;
std::stack<char> operation_stack;
unsigned int number = 0;
bool compuate_flag = false;
for (int i = 0; i < s.length(); i++){
if (s[i] == ' '){
continue;
}
switch(STATE){
case STATE_BEGIN:
if (s[i] >= '0' && s[i] <= '9'){
STATE = NUMBER_STATE;
}
else{
STATE = OPERATION_STATE;
}
i--;
break;
case NUMBER_STATE:
if (s[i] >= '0' && s[i] <= '9'){
number = number * 10 + s[i] - '0';
}
else{
number_stack.push(number);
if (compuate_flag){
compute(number_stack, operation_stack);
}
number = 0;
i--;
STATE = OPERATION_STATE;
}
break;
case OPERATION_STATE:
if (s[i] == '+' || s[i] == '-'){
operation_stack.push(s[i]);
compuate_flag = true;
}
else if (s[i] == '('){
STATE = NUMBER_STATE;
compuate_flag = false;
}
else if (s[i] >= '0' && s[i] <= '9'){
STATE = NUMBER_STATE;
i--;
}
else if (s[i] == ')'){
compute(number_stack, operation_stack);
}
break;
}
}
if (number != 0){
number_stack.push(number);
compute(number_stack, operation_stack);
}
if (number == 0 && number_stack.empty()){
return 0;
}
return number_stack.top();
}
};
#include <iostream>
#include <stack>
#include <cctype>
using namespace std;
class Solution {
private:
stack<int> num;
stack<char> op;
int pri(char a){
switch(a){
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '(': return 3;
default: return -1;
}
}
void cal(){
int b=num.top();num.pop();
int a=num.top();num.pop();
switch(op.top()){
case '+':num.push(a+b);break;
case '-':num.push(a-b);break;
case '*':num.push(a*b);break;
case '/':num.push(a/b);break;
}
op.pop();
}
public:
int calculate(string s) {
string ss;
for(int i=0;i<(int)s.size();i++){
if(isdigit(s[i]))
ss+=s[i];
else if(s[i]==' ') continue;
else{
if(!ss.empty()){
num.push(stoi(ss));
ss.clear();
}
if(op.empty()||s[i]=='('||pri(op.top())<pri(s[i]) )
op.push(s[i]);
else if(s[i]==')'){
while(op.top()!='(') cal();
op.pop();
}
else{
while(!op.empty()&&pri(op.top())<=pri(s[i])) cal();
op.push(s[i]);
}
}
}
if(!ss.empty()) num.push(stoi(ss));
while(!op.empty()) cal();
return num.top();
}
};
int main(){
Solution s;
cout<<s.calculate("(1+(4+5+2)-3)+(6+8)")<<endl;
}