Evaluation of Postfix Expression
PROBLEM :
Given a postfix expression, the task is to evaluate the expression and print the final value.
Input:
The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an postfix expression.
Output:
For each test case, evaluate the postfix expression and print the value.
Constraints:
1 <= T <= 100
1 <= length of expression <= 100
Example:
Input:
2
231*+9-
123+*8-
Output:
-4
-3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
#include<stack>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int Postfix(string str){
int ans=0 ;
stack<int> s ;
for(int i=0;i<str.length();i++){
if(isdigit(str[i]))
s.push(str[i]-'0') ;
else{
int o2=s.top() ; s.pop() ;
int o1=s.top() ; s.pop() ;
switch(str[i]){
case '+' : s.push(o1+o2) ; break ;
case '-' : s.push(o1-o2) ; break ;
case '*' : s.push(o1*o2) ; break ;
case '/' : s.push(o1/o2) ; break ;
case '^' : s.push(pow(o1,o2)) ; break ;
}
}
}
return s.top() ;
}
int main(){
int t ;
cin>>t ;
while(t--){
string str ;
cin>>str ;
cout<<Postfix(str) ;
cout<<endl ;
}
return 0;
}
--------------------------------------------------------------------------------
Given a postfix expression, the task is to evaluate the expression and print the final value.
Input:
The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an postfix expression.
Output:
For each test case, evaluate the postfix expression and print the value.
Constraints:
1 <= T <= 100
1 <= length of expression <= 100
Example:
Input:
2
231*+9-
123+*8-
Output:
-4
-3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<math.h>
#include<stack>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int Postfix(string str){
int ans=0 ;
stack<int> s ;
for(int i=0;i<str.length();i++){
if(isdigit(str[i]))
s.push(str[i]-'0') ;
else{
int o2=s.top() ; s.pop() ;
int o1=s.top() ; s.pop() ;
switch(str[i]){
case '+' : s.push(o1+o2) ; break ;
case '-' : s.push(o1-o2) ; break ;
case '*' : s.push(o1*o2) ; break ;
case '/' : s.push(o1/o2) ; break ;
case '^' : s.push(pow(o1,o2)) ; break ;
}
}
}
return s.top() ;
}
int main(){
int t ;
cin>>t ;
while(t--){
string str ;
cin>>str ;
cout<<Postfix(str) ;
cout<<endl ;
}
return 0;
}
--------------------------------------------------------------------------------
Comments
Post a Comment