Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int priority(char c){
- if(c=='*'||c=='/') return 1;
- else return 0;
- }
- int output(int a, int b, char c){
- if(c=='+')
- return a+b;
- else if(c=='-')
- return a-b;
- else if(c=='*')
- return a*b;
- else if(c=='/')
- return a/b;
- }
- int evaluateEquation(string equ){
- stack<int> numbers;
- stack<char> opa;
- int num=0;
- for(int i=0;i<equ.size();i++){
- if(equ[i]>='0'&&equ[i]<='9'){
- num=num*10+(equ[i]-48);
- }
- else{
- numbers.push(num);
- num=0;
- while(!opa.empty()&&priority(opa.top())>=priority(equ[i])){
- int b=numbers.top();
- numbers.pop();
- int a=numbers.top();
- numbers.pop();
- int res=output(a, b, opa.top());
- //cout<<res<<endl;
- opa.pop();
- numbers.push(res);
- }
- opa.push(equ[i]);
- }
- }
- if(num!=0)
- numbers.push(num);
- while(!opa.empty()){
- int b=numbers.top();
- numbers.pop();
- int a=numbers.top();
- numbers.pop();
- int res=output(a, b, opa.top());
- opa.pop();
- numbers.push(res);
- }
- return numbers.top();
- }
- int main(){
- string equ;
- cin>>equ;
- cout<<evaluateEquation(equ)<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment