19009 后缀表达式

思路

  1. **输入处理**:读取输入的后缀表达式,去掉末尾的`@`符号。

  2. **使用栈计算后缀表达式**:

  • 遍历表达式中的每个字符。

  • 如果是数字,压入栈中。

  • 如果是运算符,从栈中弹出两个数字进行运算,并将结果压入栈中。

  1. **输出结果**:栈中最后剩下的数字即为表达式的结果。

伪代码

```

function evaluate_postfix(expression):

stack = []

for token in expression.split():

if token is a digit:

stack.push(int(token))

else if token is an operator:

b = stack.pop()

a = stack.pop()

result = perform_operation(a, b, token)

stack.push(result)

return stack.pop()

function perform_operation(a, b, operator):

if operator == '+':

return a + b

if operator == '-':

return a - b

if operator == '*':

return a * b

if operator == '/':

return a / b

function main():

while input is not EOF:

expression = read_input().strip('@')

result = evaluate_postfix(expression)

print(result)

```

C++代码

cpp 复制代码
#include <iostream>
#include <stack>
#include <sstream>
#include <string>

int main() {
    std::string input;
    std::getline(std::cin, input);

    std::stack<int> s;
    std::istringstream iss(input);
    std::string token;

    while (iss >> token) {
        if (token == "@") {
            break;
        } else if (isdigit(token[0])) {
            s.push(std::stoi(token));
        } else {
            for (char op : token) {
                if (op == '@') {
                    break;
                }
                int b = s.top(); s.pop();
                int a = s.top(); s.pop();
                if (op == '+') {
                    s.push(a + b);
                } else if (op == '-') {
                    s.push(a - b);
                } else if (op == '*') {
                    s.push(a * b);
                } else if (op == '/') {
                    s.push(a / b);
                }
            }
        }
    }

    std::cout << s.top() << std::endl;
    return 0;
}

总结

  1. **输入处理**:读取并去掉末尾的`@`符号。

  2. **使用栈计算后缀表达式**:遍历表达式,数字压栈,运算符弹出两个数字计算并压栈。

  3. **输出结果**:栈中最后剩下的数字即为结果。

相关推荐
不当菜鸡的程序媛5 小时前
Flow Matching|什么是“预测速度场 vt=ε−x”?
人工智能·算法·机器学习
Pointer Pursuit5 小时前
C++——二叉搜索树
开发语言·c++
澪吟5 小时前
C++ 从入门到进阶:核心知识与学习指南
开发语言·c++
sali-tec5 小时前
C# 基于halcon的视觉工作流-章58-输出点云图
开发语言·人工智能·算法·计算机视觉·c#
_OP_CHEN5 小时前
算法基础篇:(四)基础算法之前缀和
c++·算法·前缀和·蓝桥杯·acm·icpc·算法竞赛
lion King7765 小时前
c++八股:explicit
开发语言·c++
初见无风6 小时前
4.3 Boost 库工具类 optional 的使用
开发语言·c++·boost
_OP_CHEN6 小时前
算法基础篇:(五)基础算法之差分——以“空间”换“时间”
c++·算法·acm·icpc·算法竞赛·差分算法·差分与前缀和
DuHz6 小时前
霍夫变换和基于时频脊线的汽车FMCW雷达干扰抑制——论文阅读
论文阅读·物联网·算法·汽车·信息与通信·毫米波雷达
秋风&萧瑟6 小时前
【C++】智能指针介绍
java·c++·算法