#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <sstream>
using namespace std;
void addNum(deque<string>& deq, int num)
{
if(!deq.empty())
{
int cur = 0;
string top = deq.back();
deq.pop_back();
if(top == "+" || top == "-")
{
deq.push_back(top);
}
else
{
cur = stoi(deq.back());
deq.pop_back();
num = top == "*" ? (cur * num) : (cur / num);
}
}
deq.push_back(to_string(num));
}
int getNum(deque<string> &deq)
{
int res = 0;
bool add = true;
string cur;
int num;
while(!deq.empty())
{
cur = deq.front();
deq.pop_front();
if(cur == "+")
add = true;
else if(cur == "-")
add = false;
else
{
num = stoi(cur);
res += add ? num : (-num);
}
}
return res;
}
vector<int> value(string str, int i)
{
deque<string> deq;
int pre = 0;
vector<int> bra(2);
while(i < str.size() && str[i] != ')')
{
if(str[i] >= '0' && str[i] <= '9')
pre = pre * 10 + str[i++] - '0';
else if(str[i] != '(')
{
addNum(deq, pre);
stringstream stream;
stream << str[i++];
string temp = stream.str();
deq.push_back(temp);
pre = 0;
}
else
{
bra = value(str, i + 1);
pre = bra[0];
i = bra[1] + 1;
}
}
addNum(deq, pre);
bra[0] = getNum(deq);
bra[1] = i;
return bra;
}
int main()
{
string str = "48*((70-65)-43)+8*1";
string str1 = "3+1*4";
cout << value(str, 0)[0] << endl;
}
公式字符串求值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.