后缀表达式
洛谷P1449
Hi~ 今天更新了两篇~ 嘿嘿~
Anyways 回归正题
输入:3.5.2.-*7.+@
输出:16
这道题的较难的地方就是输入 但是也不是太难🙃
算了 懒得写了 注释在程序里~
//
// main.cpp
// 后缀表达式
//
// Created by Helen on 2020/7/26.
// Copyright © 2020 Helen. All rights reserved.
//
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
string s;
int n,ans;
stack<int>num;
int main ()
{
cin >> s; // 输入原字符串
for (int i=0;i<s.size();i++)
{
if (s[i]>='0' && s[i]<='9') // 如果是数字
{
n*=10; // 乘10
n+=s[i]-'0'; // 转为数字
}
else if (s[i]=='.') // 如果是'.'
{
num.push(n); // 把前面处理的数字push进栈里
n=0;
}
else if (s[i]=='+') // 判断加减乘除就好啦
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
ans=a+b;
num.push(ans);
}
else if (s[i]=='-')
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
ans=b-a;
num.push(ans);
}
else if (s[i]=='*')
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
ans=a*b;
num.push(ans);
}
else if (s[i]=='/')
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
ans=b/a;
num.push(ans);
}
}
cout << num.top() << endl; // 就剩一个数字了嘛 所以直接输出
}
好啦 希望你看懂了 Au revoir~
----------------------------------------✂︎---------------------------------------------
此题解已经AC 欢迎指出更多优化方法~