本文主要是介绍四则运算/华为机试(C/C++),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
请实现如下接口
/* 功能:四则运算
* 输入:strExpression:字符串格式的算术表达式,如: "3+2*{1+2*[-4/(8-6)+7]}"
* 返回:算术表达式的计算结果
*/
public static int calculate(String strExpression)
{
/* 请实现*/
return 0;
}
约束:
-
pucExpression字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。
-
pucExpression算术表达式的有效性由调用者保证;
输入描述:
输入一个算术表达式
输出描述:
得到计算结果
示例1
输入
3+2*{1+2*[-4/(8-6)+7]}
输出
25
代码:借用
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int main()
{string s;while (cin >> s) {stack<char> opera;vector<int> numcnt;string s1;//后缀表达式//中缀表达式转后缀表达式for (int i = 0; i<s.size(); i++) {if (s[i] >= '0'&&s[i] <= '9') {int tmp = 0;while (s[i] >= '0'&&s[i] <= '9') {tmp++;s1 += s[i];i++;}i--;numcnt.push_back(tmp);}else if (s[i] == '-' || s[i] == '+') {if (s[i] == '-' && (s[i - 1] == '(' || s[i - 1] == '[' || s[i - 1] == '{'))s1 += '0';while (!opera.empty() && (opera.top() == '*' || opera.top() == '/' || opera.top() == '+' || opera.top() == '-')) {s1 += opera.top();opera.pop();}opera.push(s[i]);}else if (s[i] == '*' || s[i] == '/') {while (!opera.empty() && (opera.top() == '*' || opera.top() == '/')) {s1 += opera.top();opera.pop();}opera.push(s[i]);}else if (s[i] == '(' || s[i] == '[' || s[i] == '{')opera.push(s[i]);else if (s[i] == ')') {while (opera.top() != '(') {s1 += opera.top();opera.pop();}opera.pop();}else if (s[i] == ']') {while (opera.top() != '[') {s1 += opera.top();opera.pop();}opera.pop();}else if (s[i] == '}') {while (opera.top() != '{') {s1 += opera.top();opera.pop();}opera.pop();}elsecout << "Invalid input!" << endl;}while (!opera.empty()) {s1 += opera.top();opera.pop();}//计算后缀表达式的值stack<int> nums;int ind = 0;for (int i = 0; i<s1.size(); i++) {if (s1[i] >= '0'&&s1[i] <= '9') {int total = 0;while (numcnt[ind]--)total = 10 * total + (s1[i++] - '0');i--;nums.push(total);ind++;}else {int tmp1 = nums.top();nums.pop();int tmp2 = nums.top();nums.pop();if (s1[i] == '+')nums.push(tmp2 + tmp1);else if (s1[i] == '-')nums.push(tmp2 - tmp1);else if (s1[i] == '*')nums.push(tmp2*tmp1);elsenums.push(tmp2 / tmp1);}}cout << nums.top() << endl;}
}
这篇关于四则运算/华为机试(C/C++)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!