Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- push numbers into stack and whenever operators comes pop top two items
- and operate on them and push the result.
- */
- long long int _stoi(string s){
- bool sign=false;
- long long int ans=0;
- int i=0;
- if(s[0]=='-'){sign=true; i++;}
- while(i<s.size()){
- ans=ans*10+(s[i]-'0');
- i++;
- }
- if(sign) return -ans;
- return ans;
- }
- class Solution {
- public:
- int evalRPN(vector<string>& arr) {
- stack<long long int> st;
- for(auto itr:arr){
- if(itr=="+" || itr=="-" || itr=="*" || itr=="/"){
- long long int b=st.top(); st.pop();
- long long int a=st.top();st.pop();
- if(itr=="+") st.push(a+b);
- else if(itr=="-") st.push(a-b);
- else if(itr=="*") st.push(a*b);
- else st.push(a/b);
- }
- else st.push(_stoi(itr));
- }
- return st.top();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement