一道华为的机试题。
问题描述:
输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值
注
1、表达式只含 +, -, *, / 四则运算符,不含括号
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,除此之外不含其它任何字符,不会出现计算溢出情况
要求实现函数:
int calculate(int len,char *expStr)
【输入】 int len: 字符串长度;
char *expStr: 表达式字符串;
【输出】 无
【返回】 计算结果
示例
1) 输入:char *expStr = “1+4*5-8/3”
函数返回:19
2) 输入:char *expStr = “8/3*3”
函数返回:6
用C++做了一个直接输入表达式字符串的代码。
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int main()
{
string str;
cin >> str;
stack<char> operC;
string strB;
string::iterator it = str.begin();
for (; it < str.end(); ++it) //这里面写了很多逻辑判断,写完后再看,发现很多逻辑可以合并
{
if (*it >= '0' && *it <= '9')
strB += *it;
if (*it == '-' || *it == '+')
{
while (! operC.empty())
{
strB += operC.top();
operC.pop();
}
operC.push(*it);
}
if (*it == '*' || *it == '/')
{
if (operC.top() == '*' || operC.top() == '/')
{
strB += operC.top();
operC.pop();
}
operC.push(*it);
}
}
if (!operC.empty())
{
while (! operC.empty())
{
strB += operC.top();
operC.pop();
}
}
cout << strB << endl; //输出后缀表达式
//计算后缀表达式的值,开辟一个新的 int元素的栈,因为计算过程中可能产生大于10的数,一位字符就不能表示了
stack<int> calcu;
it = strB.begin();
for (; it < strB.end(); ++it)
{
if (*it >= '0' && *it <= '9')
{
calcu.push(*it - '0');
}
else
{
int a = calcu.top();
calcu.pop();
int b = calcu.top();
calcu.pop();
int sum;
switch (*it)
{
case '+':
sum = a + b;
break;
case '-':
sum = b - a;
break;
case '*':
sum = a * b;
break;
case '/':
sum = b / a;
break;
}
calcu.push(sum);
}
}
cout << calcu.top() << endl; //输出计算结果
system("pause");
return 0;
}
另外关于任意整数和带有括号等的运算可以参考另一人博客:
http://blog.csdn.net/that163/article/details/7451823
http://blog.csdn.net/that163/article/details/7558268