zoukankan      html  css  js  c++  java
  • [UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用

    题目描述

    In a postfix expression, operators follow their operands. For example, [ 5 2 * ] is interpreted as 5 * 2. If there are multiple operators, each operator appears after its last operand. Here are more examples, showing how postfix compares to parenthesized expressions:
    6   3 + 5 ∗ 2 − 6 3 + 5 * 2 − 6 3+52 等同 ( ( 6 + 3 ) ∗ 5 ) – 2 ) ((6 + 3) * 5) – 2) ((6+3)5)2)

    4   3   2 ∗ + 4 3 2 * + 4 3 2+ 等同 4 + ( 3 ∗ 2 ) 4 + (3 * 2) 4+(32)
    These examples show that the operand affected by an operator can be the result of a previous calculation.
    Here is what you need to do: Given an integer postfix expression, you must calculate and print its value.

    输入

    Each input will consist of a single test case. Your program will be run multiple times on different inputs.
    A single input line will contain a postfix expression containing single digit integers and operators from the following set: { +, –, /, * } (add, subtract, divide, multiply). There will be a single space between each digit and and operator. The line will contain no more than 64 operators and numbers, total.

    输出

    Output will be a single integer on a line by itself.
    样例输入 Copy

    【样例16 3 + 5 * 2 –
    【样例26 3 + 5 2 * *
    【样例34 3 2 * + 
    

    样例输出 Copy

    【样例143
    【样例290
    【样例310
    
    stack<ll> st;
    int main() {
    	char c;
    	while(cin >> c) {
    		if(isdigit(c)){
    			st.push(c - '0');
    		}else{
    			ll a = st.top();
    			st.pop();
    			ll b = st.top();
    			st.pop();
    			if(c == '+') st.push(a + b);
    			else if(c == '-') st.push(b - a);
    			else if(c == '*') st.push(a * b);
    			else st.push(b / a);
    		}
    	}
    	cout << st.top() << endl;
    	return 0;
    }
    /**
    
    
    **/
    
    
  • 相关阅读:
    ie8 不能加载dll的问题解决
    Delphi 释放数组中的数据
    CSS: 首字母字体变大时下划线不对齐的解决方法
    谈谈一些有趣的CSS题目(十三)-- 巧妙地制作背景色渐变动画!
    吃透css3之3d属性--perspective和transform
    vue-cli中的webpack配置
    转载 webstrom识别 React语法
    CSS 布局整理(************************************************)
    巧用chrome开发者工具
    详解Webpack2的那些路径
  • 原文地址:https://www.cnblogs.com/PushyTao/p/15459789.html
Copyright © 2011-2022 走看看