Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.

 1 class Solution {
 2 public:
 3     int calculate(string s) {
 4         int n=s.length();
 5         if(n<1)
 6             return -1;
 7         stack<int> num;
 8         stack<char> symbol;
 9         symbol.push('+');
10         int i;
11         for(i=0;i<n;)
12         {
13             if(s[i]=='+'||s[i]=='-'||s[i]=='(')
14             {
15                 symbol.push(s[i]);
16                 i++;
17             }
18             else if(s[i]==' ') i++;
19                  else if(s[i]==')')
20                  {
21                      i++;
22                      int right=0;
23                      int tmp=num.top();
24                      num.pop();
25                      char sym=symbol.top();
26                      symbol.pop();
27                      while(sym!='(')
28                      {
29                          
30                          if(sym=='-') tmp=-tmp;
31                          right+=tmp;
32                          tmp=num.top();
33                          num.pop();
34                          sym=symbol.top();
35                          symbol.pop();
36                      }
37                      right+=tmp;
38                      num.push(right);
39                  }
40                  else
41                  {
42                      int right=0;
43                      while(i<n&&s[i]>='0'&&s[i]<='9')
44                      {
45                          right=right*10+s[i]-'0';
46                          i++;
47                      }
48                      num.push(right);
49                  }
50         }
51         int res=0;
52         int tmp_r;
53         char sym_r;
54         while(!symbol.empty())
55         {
56             tmp_r=num.top();
57             sym_r=symbol.top();
58             num.pop();
59             symbol.pop();
60             if(sym_r=='-') tmp_r=-tmp_r;
61             res+=tmp_r;
62         }
63         return res;
64     }
65 };
原文地址:https://www.cnblogs.com/zl1991/p/4670124.html