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 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了