华为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 <iostream>    
#include <vector>
#include <string>
#include <stack>
#include <map>
#include <algorithm>

using namespace std;

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

void getExpression(string str)
{
	stack<char> 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<int> 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()<<endl;
	cout << "true";
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值