码迷,mamicode.com
首页 > 其他好文 > 详细

Basic Calculator

时间:2015-07-23 13:35:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Basic Calculator

标签:

原文地址:http://www.cnblogs.com/zl1991/p/4670124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!