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.
==================
基本的+,-,*,/计算,利用栈
====
思路:
申请两个栈,一个符号栈op,一个数字栈num,
代码:
class Solution { public: int calculate(string s) { stack<char> op; stack<int> num; const int n = s.size(); char ch; int tmp = 0; int a = 0; for(int i = 0;i<n;i++){ ch = s[i]; if(ch==' ') continue; else if(ch=='*' || ch=='/' || ch=='+' || ch=='-'){ op.push(ch); }else if(isdigit(ch)){ tmp = tmp*10+ch-'0'; while(i<n && isdigit(ch=s[++i])){ tmp = tmp*10+ch-'0'; } if(!op.empty()){ char curr_op = op.top(); if(curr_op == '*'){ int a = num.top();num.pop();op.pop(); num.push(a*tmp); }else if(curr_op == '/'){ a = num.top();num.pop();op.pop(); num.push(a/tmp); }else{ if(curr_op == '-') tmp *=-1; num.push(tmp); } }else{ num.push(tmp); } tmp = 0; if(i==n) break; i--; } } while(!op.empty()){ int a = num.top();num.pop(); int b = num.top();num.pop(); //char ch = op.top(); op.pop(); num.push(a+b); }///while int re = num.top();num.pop(); return re; } };