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 };

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值