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
#include<algorithm>
#include<string>
#include<stack>
class Solution {
stack<int> st;
string str;
int i;
public:
int calculate(string s) {
i = 0;
str = s;
while(i<str.size ()){
char c = str[i];
if(isspace (c)){
++i;
continue;
}
if(isdigit (c)){
int v = getInt ();
st.push (v);
continue;
}
if(isoperator (c)){
if(c == '*'){
++i;
int v = getInt ();
int v1 = st.top ();
st.pop ();
v1 *= v;
st.push (v1);
continue;
}
if(c == '/'){
++i;
int v = getInt ();
int v1 = st.top ();
st.pop ();
v1 /= v;
st.push (v1);
continue;
}
if(c == '-'){
++i;
int v = getInt ();
st.push (-1 * v);
continue;
}
if(c == '+'){
++i;
int v = getInt ();
st.push ( v);
continue;
}
}
}
int ret = 0;
while(!st.empty ()){
ret += st.top ();
st.pop ();
}
return ret;
}
bool isoperator(char c){
return c == '+' || c =='-' || c == '*' || c == '/';
}
int getInt(){
string res;
while(i<str.size ()){
char c = str[i];
if(isspace (c))
++i;
else if(isoperator (c))
break;
else if(isdigit (c)){
res.push_back (c);
++i;
}
}
return atoi (res.data ());
}
};
简单的加减剩除计算器:
1.先读一个数,入栈
2.A读一个符号,如果读到 ‘*’ 或 ‘/’ ,一个数出栈,继续在字符串里读一个数,两个数做相应的’*’ 或’/’, 压入栈。
2.B,如果这个符号是+, 再读一个数直接入栈,如果是-号,则转为负数再入栈。
3.最后对栈里的所有数做加法,返回结果