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 };
复制代码

 

posted @   鸭子船长  阅读(148)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示