Skip to content

Commit

Permalink
Create basic-calculator-iii.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jan 23, 2018
1 parent a4383f0 commit 788e2d9
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions C++/basic-calculator-iii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Time: O(n)
// Space: O(n)

// Support +, -, *, /.
class Solution {
public:
int calculate(string s) {
stack<int64_t> operands;
stack<char> operators;
string operand;
for (int i = s.length() - 1; i >= 0; --i) {
if (isdigit(s[i])) {
operand.push_back(s[i]);
if (i == 0 || !isdigit(s[i - 1])) {
reverse(operand.begin(), operand.end());
operands.emplace(stol(operand));
operand.clear();
}
} else if (s[i] == ')' || s[i] == '*' ||
s[i] == '/') {
operators.emplace(s[i]);
} else if (s[i] == '+' || s[i] == '-') {
while (!operators.empty() && (operators.top() == '*' ||
operators.top() == '/')) {
compute(operands, operators);
}
operators.emplace(s[i]);
} else if (s[i] == '(') {
// operators at least one element, i.e. ')'.
while (operators.top() != ')') {
compute(operands, operators);
}
operators.pop();
}
}
while (!operators.empty()) {
compute(operands, operators);
}
return operands.top();
}

void compute(stack<int64_t>& operands, stack<char>& operators) {
const int64_t left = operands.top();
operands.pop();
const int64_t right = operands.top();
operands.pop();
const char op = operators.top();
operators.pop();
if (op == '+') {
operands.emplace(left + right);
} else if (op == '-') {
operands.emplace(left - right);
} else if (op == '*') {
operands.emplace(left * right);
} else if (op == '/') {
operands.emplace(left / right);
}
}
};

0 comments on commit 788e2d9

Please sign in to comment.