九度OJ 1019:简单计算器

#include <iostream>
#include <stack>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <regex>
using namespace std;
/**
* 九度:1019:简单计算器
* [10/9/2014 liu]
*/

// 1、将中缀表达式转换成前缀表达式或者是后缀表达式


map<string,int> mapOperator;

int getOperPriority(string a)
{
// find函数返回的是一个迭代器
std::map<string, int>::iterator pos;
pos = mapOperator.find(a);
return pos->second;
}

vector<string> split(string str, string pattern)
{
vector<string> v;
int size = str.length();
str += pattern; // 这句话要注意
while (str !="")
{
int index = str.find(pattern);
string strtemp = str.substr(0, index);
str.erase(0, index + 1);
v.push_back(strtemp);
}
return v;
}
vector<string> centertopreExpression(vector<string> str)
{
// 
mapOperator.insert(make_pair("+", 1));
mapOperator.insert(make_pair("-", 1));
mapOperator.insert(make_pair("*", 2));
mapOperator.insert(make_pair("/", 2));

// 3+4*5-4/3 
// 定义两个栈
stack<string> operatorStack; // 操作符栈
stack<string> numStack; // 操作数栈
for (int i = str.size() - 1; i >= 0; i--)
{
if (isdigit(str[i][0])) // isdigit 判断字符
{
numStack.push(str[i]);
}
else
{
if (operatorStack.empty())
operatorStack.push(str[i]);
else
{
if (getOperPriority(str[i]) >= getOperPriority(operatorStack.top()))
{
operatorStack.push(str[i]);
}
else
{
numStack.push(operatorStack.top());
operatorStack.pop();
while (!operatorStack.empty() && 
getOperPriority(str[i]) < getOperPriority(operatorStack.top()))
{
numStack.push(operatorStack.top());
operatorStack.pop();
}
operatorStack.push(str[i]);
}
}
}

}
while(!operatorStack.empty())
{
numStack.push(operatorStack.top());
operatorStack.pop();
}
int n = numStack.size();
vector<string> strtemp; 
int temp = 0;
while (!numStack.empty())
{
strtemp.push_back(numStack.top());
numStack.pop();
temp++;
}

return strtemp;

}

void calculate(stack<double> &intStack,string str)
{
double a = intStack.top();
intStack.pop();

double b = intStack.top();
intStack.pop();
if (str == "*")
{
intStack.push(a*b);
}
else if (str == "/" )
{
intStack.push(a / b);
}
else if (str == "-")
{
intStack.push(a -b);
}
else if (str == "+")
{
intStack.push(a+b);
}
}
int GetResult(string str)
{
vector<string> strvec = split(str, " ");
vector<string> resultstr = centertopreExpression(strvec);

stack<double> intStack;
for (int i = resultstr.size() - 1; i >= 0; i--)
{
if (isdigit(resultstr[i][0]))
{
int a = atoi(resultstr[i].c_str());
intStack.push(a);
}
else
{
calculate(intStack, resultstr[i]);

}
}
double a = intStack.top();
return a;
}
int main()
{
string str;
while (getline(cin,str))
{
printf("%d", GetResult(str));
}
return 0;
}

上面的代码估计不能AC,做的题目太少,但是功能应该实现了

主要是使用了中缀表达式转换成前缀表达式,算是实现了一种算法,参考如下博客

http://blog.csdn.net/antineutrino/article/details/6763722


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值