求解逆波兰表达式


描述
编写函数int add(char s[]);计算字符串形式的逆波兰表达式(即两个操作数在前,计算符在后)。本题内,保证每个操作数均为1位数。操作符有'+','-','*','/'四种。且保证计算过程中除法运算全部为整数除法,结果为整数。
如23+4*,,结果20
Write a function int add (char s []); Calculate the string form of reverse Polish notation (ie, the first is two operands, then the operator). This problem, to ensure that each of the operands are 1-digit. The operator have only four: '+', '-', '*', '/'. And to ensure that the division operation in the calculation process for all the integer division, the result is an integer.
Such as 23+4*, the result is 20.
 
输入
一行字符串,长度不超过20。
Input a string, no more then 20 characters.
 
输出
逆波兰表达式的计算结果。
Output the result of reverse Polish notation.
 
输入样例
23+4*
 
输出样例
20


#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;
int calcu(int num1,int num2,char op);
stack <int> s1;
char s[1000];
int a[1000];
int main()
{
 int n,i,num1,num2;
 int result;
 
 gets(s);
 
 n=strlen(s);
 
 for(i=0; i<n; i++)
 {
  if(s[i]>=48&&s[i]<=57)
  {
   a[i]=s[i]-'0';
   result=a[i];
   s1.push(a[i]);
  }
  else
  {
   num2=s1.top();
   s1.pop();
   num1=s1.top();
   s1.pop();
   result=calcu(num1,num2,s[i]);
   s1.push(result);
  }
 }
 printf("%d\n",result);
}

int calcu(int num1,int num2,char op)
{
 int result;
 if(op=='+')
 {
  result=num1+num2;
 }
 if(op=='-')
 {
  result=num1-num2;
 }
 if(op=='*')
 {
  result=num1*num2;
 }
 if(op=='/')
 {
  result=num1/num2;
 }
 return result;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值