Basic Calculator II - Medium - L
Published:
Question
- https://leetcode.com/problems/basic-calculator-ii/
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Approach
- Stacks with + storage and storing -ve sign.
Solution
class Solution {
public:
int calculate(string s) {
stack<int> st;
int n = s.size();
int i=0;
char sign='+';
while(i<n){
int num=0;
int fl=0;
while(i<n && s[i]==' '){
i++;
}
while(i<n && s[i]>='0' && s[i]<='9'){
fl=1;
num=10*num+(s[i]-'0');
i++;
}
if(sign=='-'){
num=-1*num;
}
if(fl==1){
st.push(num);
}
if(sign=='/'){
int val = st.top();
st.pop();
int val1 = st.top();
st.pop();
st.push(val1/val);
}
if(sign=='*'){
int val = st.top();
st.pop();
int val1 = st.top();
st.pop();
st.push(val1*val);
}
if(i<n && s[i]!=' '){
sign=s[i];
}
i++;
}
int ans=0;
while(!st.empty()){
ans+=st.top();
st.pop();
}
return ans;
}
};