华为OJ表达式求值

来源:互联网 发布:淘宝宝贝推荐模板 编辑:程序博客网 时间:2024/06/06 10:44

描述

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

输入字符串长度不超过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/52245233void 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]);}elses.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 0
原创粉丝点击