zoukankan      html  css  js  c++  java
  • 后缀表达式

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

    将数字存入栈中,遇到符号就计算栈顶和它下面的一个数并将得到的新得数存入栈。

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cmath>
     4 #include<cstring>
     5 #include<algorithm>
     6 #include<stack>
     7 using namespace std;
     8 const int maxn = 500;
     9 char a[maxn];
    10 void solve(char a[])
    11 {
    12     stack<int>num;
    13     int l = strlen(a), n = 0;
    14     for(int i = 0; i < l; ++i)
    15     {
    16         if(a[i] >= '0' && a[i] <= '9')    //分离运算数 
    17         {
    18             n += a[i] - '0';    //n用来暂时储存所得的数 
    19             if(a[i + 1] >= '0' && a[i + 1] <= '9') n *= 10;    
    20             else {num.push(n); n = 0;}
    21         }
    22         if(a[i] == '+')
    23         {
    24             int x = num.top(); num.pop();
    25             num.top() += x;
    26         }
    27         if(a[i] == '-')
    28         {
    29             int x = num.top(); num.pop();
    30             num.top() -= x;
    31         }
    32         if(a[i] == '*')
    33         {
    34             int x = num.top(); num.pop();
    35             num.top() *= x;
    36         }
    37         if(a[i] == '/')
    38         {
    39             int x = num.top(); num.pop();
    40             num.top() /= x;
    41         }
    42     }
    43     printf("%d\n", num.top());
    44     return;
    45 }
    46 int main()
    47 {
    48     a[0] = getchar();
    49     int i = 0;
    50     while(a[i] != '@') a[++i] = getchar();
    51     solve(a);
    52     return 0;
    53 }

     

  • 相关阅读:
    Css_加载样式
    Mvc4_@RenderBody()和@RenderSection()
    C#_观察者模式
    Mvc4_MvcPager 概述
    Mvc4_Area的应用
    Nginx 服务器性能参数设置
    Nginx变量的实现机制
    天下无雾
    Nginx Http框架的理解
    【转】websocket协议规范
  • 原文地址:https://www.cnblogs.com/mrclr/p/8324389.html
Copyright © 2011-2022 走看看