华为OJ表达式求值

描述

给定一个字符串描述的算术表达式,计算出结果值。

输入字符串长度不超过100,合法的字符包括+, -, *, /, (, )0-9,字符串内容的合法性及表达式语法的合法性由做题者检查。本题目只涉及整型计算。

  •  

        /*

        功能对输入的字符串表达式进行求值计算,并输出结果。

     

        输入:String inputString:表达式字符串   

             

        返回: int :正常返回true,失败返回false

        */

     

        public static boolean calculate(String inputString)

        {

            /*在这里实现功能*/

           return true;

        }

     

  • 获取计算结果(int型)

        public static int getResult()

        {

            /*在这里实现功能*/

           return 0;

        }

     

     


知识点
运行时间限制 10M
内存限制 128
输入

输入算术表达式

输出

计算出结果值

样例输入 400+5
样例输出 405 true
#include     
#include 
#include 
#include 
#include 
#include 

using namespace std;

map priority;//保存运算符优先级
vector vec;//保存后缀表达式
//函数getExpression用于获取字符串的后缀表达式
//输入:str中缀表达式字符串
//输出:vec后缀表达式
//算法参考网址:http://blog.csdn.net/u012507347/article/details/52245233

void getExpression(string str)
{
	stack s;	//保存运算符
	for (int i = 0; i < str.length(); i++)
	{
		if (isalnum(str[i]))
		{
			string num;
			while (isalnum(str[i]))
			{
				num.push_back(str[i]);
				i++;
			}
			vec.push_back(num);
			i--;
		}
		else if (str[i] == '(')
		{
			s.push(str[i]);
		}
			
		else if (str[i] == ')')
		{
			while (s.top() != '(')
			{
				string tmp;
				tmp.push_back(s.top());
				vec.push_back(tmp);
				s.pop();
			}
			s.pop();
		}
		else
		{
			if(!s.empty() && priority[s.top()] <= priority[str[i]] 
				&& s.top() != '(')
			{
				string tmp;
				tmp.push_back(s.top());
				vec.push_back(tmp);
				s.pop();
				s.push(str[i]);			
			}
			else
				s.push(str[i]);
		}
	}
	while (!s.empty())
	{
		string tmp;
		tmp.push_back(s.top());
		vec.push_back(tmp);
		s.pop();
	}
}

//计算后缀表达式的结果
int computerExp()
{
	stack s;
	for (int i = 0; i < vec.size(); i++)
	{
		if (isalnum(vec[i][0]))
		{
			int num = atoi(vec[i].c_str());
			s.push(num);
		}
		else
		{
			int value1 = s.top();
			s.pop();
			int value2 = s.top();
			s.pop();
			int value3;
			switch (vec[i][0])
			{
			case '+':
				value3 = value2 + value1;
				break;
			case '-':
				value3 = value2 - value1;
				break;
			case '*':
				value3 = value2 * value1;
				break;
			case '/':
				value3 = value2 / value1;
				break;
			}
			s.push(value3);
		}
	}
	return s.top();
}

void main()
{
	priority['+'] = 1;
	priority['-'] = 1;
	priority['*'] = 0;
	priority['/'] = 0;
	string str;
	cin >> str;
	getExpression(str);
	cout << computerExp()<


你可能感兴趣的:(华为OJ)