C++后缀表达式的值

题目描述

从键盘读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。

比如,转换成后缀表达式为:,在字符数组A中的形式为:

 

 

1679970540252.gif

栈中的变化情况:

1679970558519.gif

运行结果:-47

提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在2^64范围内,如有除法保证能整除。

输入格式

一个后缀表达式。

输出格式

一个后缀表达式的值。

样例

【样例输入】

16 9 4 3 +*-@

【样例输出】

-47

 题解:

#include <iostream>
#include <stack>
#include <string>
using namespace std;

stack<long long> s;

int main() {
    string a;
    long long t = -1, m, n, ans, i = 0;
    getline(cin, a);
    while (a[i] != '@') {
        if (a[i] >= '0' && a[i] <= '9') {
            if (t == -1) {
                t = a[i] - '0';
                s.push(t);
            } else {
                t = s.top();
                s.pop();
                t = t * 10 + (a[i] - '0');
                s.push(t);
            }
        }
        if (a[i] == ' ') {
            t = -1;
        }
        if (a[i] == '+') {
            m = s.top();
            s.pop();
            n = s.top();
            s.pop();
            ans = m + n;
            s.push(ans);
        }
        if (a[i] == '-') {
            m = s.top();
            s.pop();
            n = s.top();
            s.pop();
            ans = n - m;
            s.push(ans);
        }
        if (a[i] == '*') {
            m = s.top();
            s.pop();
            n = s.top();
            s.pop();
            ans = n * m;
            s.push(ans);
        }
        if (a[i] == '/') {
            m = s.top();
            s.pop();
            n = s.top();
            s.pop();
            ans = n / m;
            s.push(ans);
        }
        i++;
    }
    cout << s.top();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值