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. **输出结果**:栈中最后剩下的数字即为结果。

相关推荐
傲世仙尊1 小时前
string增删查改-insert-erase-replace与find加substr组合技
c++
小羊没烦恼!2 小时前
异步编程:线程概述及使用
java·开发语言·mysql·算法·c#
wanderist.2 小时前
202609CSP认证P3
算法
云淡风轻~窗明几净2 小时前
角谷猜想最接近严格证明的测试 Version1.1.1
人工智能·算法·机器学习·图论
机器学习之心3 小时前
PINN × SVM × NSGA-II × 熵权TOPSIS:一套跑通「建模—优化—决策」的多目标优化框架
算法·机器学习·支持向量机
·present·3 小时前
CSAPP(lecture 3)
c++
别动我齐刘海3 小时前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
basketball6163 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
fish_zzzz4 小时前
笔记-论数据结构1
数据结构
荆棘鸟智能4 小时前
短历时洪水预报算法实践:水文模型与 LightGBM 残差订正融合
人工智能·算法·机器人