-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculatorII.hpp
100 lines (86 loc) · 1.85 KB
/
BasicCalculatorII.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//Basic Calculator II
//
//Implement a basic calculator to evaluate a simple expression string.
//
//The expression string contains only non - negative integers, +, -, *, /
//operators and empty spaces.The integer division should truncate toward zero.
//
//You may assume that the given expression is always valid.
//
//Some examples :
//"3+2*2" = 7
//" 3/2 " = 1
//" 3+5 / 2 " = 5
//Note : Do not use the eval built - in library function.
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
int calculate(string s)
{
if (s.empty())
return 0;
std::vector<int> stackOPNo;
std::vector<std::string> stackOP;
index = 0;
std::string str;
while ("" != (str = getElement(s)))
{
if ("+" == str
|| "-" == str)
stackOP.push_back(str);
else if ("*" == str
|| "/" == str)
{
int val = ("*" == str) ?
stackOPNo.back() * atoi(getElement(s).c_str())
: stackOPNo.back() / atoi(getElement(s).c_str());
stackOPNo.pop_back();
stackOPNo.push_back(val);
}
else
{
stackOPNo.push_back(atoi(str.c_str()));
}
}
while (!stackOP.empty())
{
std::string strOP = stackOP.front();
int val = ("+" == strOP) ?
stackOPNo[0] + stackOPNo[1]
: stackOPNo[0] - stackOPNo[1];
stackOPNo.erase(stackOPNo.begin(),stackOPNo.begin()+1);
stackOPNo.insert(stackOPNo.begin(), val);
stackOP.pop_back();
}
return stackOPNo.front();
}
std::string getElement(std::string &str)
{
if (index >= str.size())
return "";
std::string tmp;
if (str[index] == ' ')
{
++index;
return getElement(str);
}
else if (str[index] == '+'
|| str[index] == '-'
|| str[index] == '*'
|| str[index] == '/')
{
tmp += str[index++];
}
else
{
while (isdigit(str[index]))
tmp += str[index++];
}
return tmp;
}// end of getElement()
private:
std::size_t index;
};