Implementation

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.4 kB
1
Indexable
Never
#include <bits/stdc++.h>
using namespace std;
// TODO: Implement this method
void solve(stack<int>&st,char c){
    int x = st.top();
        st.pop();

        int y = st.top();
        st.pop();
        if (c == '+') {
            st.push(y + x);
        }

        else if (c == '-') {
            st.push(y - x);
        }
        else if (c == '*') {
            st.push(y * x);
        }

}
int postfixExpression(string s)
{
    stack<int> st;
     string str="";
    for(int i=0;i<s.length();i++)
    {
        if(s[i]>='0' and s[i]<='9'){

            str=str+s[i];

        }
        else if(s[i]=='+' or s[i]=='-' or s[i]=='*'){
            solve(st,s[i]);
        }
        else if(str.size() and (s[i]==' ' or (i==s.length()-1))){
            st.push(stoi(str));
            str="";
        }

        
    }    
    return st.empty() ? stoi(str) : st.top();
}

// NOTE: Please do not modify this function
int main()
{
    string s;
    getline(cin, s);
    int res = postfixExpression(s);
    cout << res << "\n";
}

/* 
Crio Methodology

Milestone 1: Understand the problem clearly
1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output & extend it to test cases
Milestone 2: Finalize approach & execution plan
1. Understand what type of problem you are solving.
     a. Obvious logic, tests ability to convert logic to code
     b. Figuring out logic
     c. Knowledge of specific domain or concepts
     d. Knowledge of specific algorithm
     e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one
3. Get to a point where you can explain your approach to a 10 year old
4. Take a stab at the high-level logic & write it down.
5. Try to offload processing to functions & keeping your main code small.
Milestone 3: Code by expanding your pseudocode
1. Make sure you name the variables, functions clearly.
2. Avoid constants in your code unless necessary; go for generic functions, you can use examples for your thinking though.
3. Use libraries as much as possible
Milestone 4: Prove to the interviewer that your code works with unit tests
1. Make sure you check boundary conditions
2. Time & storage complexity
3. Suggest optimizations if applicable
*/