后缀表达式-LuoguP1449

后缀表达式

后缀表达式传送门
这个是所有识别表达式中最

的一个。每次加入一些元素, 如果碰到符号就把前俩进行运算, 然后搞进去, 继续。这样一个思路就可以想到可以用stack来解决这道水题。我这个人懒得手写,直接用STL了我有一个很大胆的想法
大佬们不喜勿喷。

水洛谷时间 - 水代码

#include <bits/stdc++.h>
using namespace std;
string s;// string a str

inline int getans(string str)  {// parameter is a str, take str to this funcitional(getans)
  stack<int> s;//They're numbers 
  int size_s = str.size();
  for (int i = 0; i < size_s; ++i) {
    if (str[i] == ' ') continue;//' ' to continue because it is haven't something
    else if (str[i] == '@') break;//if this is end('@) and break
    else if (str[i] >= '0' && str[i] <= '9') {//if str[i] is a number
      int sum = 0;//this number is zero
      while (str[i] >= '0' && str[i] <= '9') {// if str[i] isn't a number->'.' and break to this while()
        sum = (sum << 3) + (sum << 1) + (str[i] ^ 48); // = "sum = sum * 10 + str[i] - '0'"
        ++i;//point to next because this is went it!
      }
      s.push(sum);// push sum -> this number
      continue;//else is nothing and leter of continue i is to next!
    }
    else if (str[i] == '-') {
      int a = s.top(); s.pop();// take out top
      int b = s.top(); s.pop();// take out top
      // it is take out in front of the operator_tag's number and do something
      s.push(b - a); // push b - a
      //why is "b - a" not "a - b" ?
      //because a is in front of the operator_tag, and b is in front of a, is in front of in front of the operator_tag
    }
    else if (str[i] == '+') {
      int a = s.top(); s.pop();
      int b = s.top(); s.pop();
      s.push(a + b); // push a + b
      //In addition, a + b = b + a
    }
    else if (str[i] == '*') {
      int a = s.top(); s.pop();
      int b = s.top(); s.pop();
      s.push(a * b); // push a * b
      //In multiplication, a * b = b * a
    }
    else if (str[i] == '/') {
      int a = s.top(); s.pop();
      int b = s.top(); s.pop();
      s.push(b / a); // push b / a
    }
  }
  return s.top();// Take out the calculated value
}

signed main() {
  cin >> s; //input str
  cout << getans(s) << endl;//output answer- number
  return 0;
}

The end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值