Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

 

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

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

 

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