描述
编写函数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.
如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.
Input a string, no more then 20 characters.
输出
逆波兰表达式的计算结果。
Output the result of reverse Polish notation.
Output the result of reverse Polish notation.
输入样例
23+4*
输出样例
20
#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;
#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];
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 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;
}