Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 27 additions & 19 deletions c++/basic-calculator-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,30 @@ int calculate(std::string s) {
std::stack<char> operators;
int n = s.length();
int currentNumber = 0;

for (int i = 0; i < n; i++) {
char c = s[i];

// If the current character is a digit, form the whole number
if (isdigit(c)) {
currentNumber = currentNumber * 10 + (c - '0');
}

// If the current character is an operator, or it's the last character

// If the current character is an operator, or it's the last
// character
if (!isdigit(c) && !isspace(c) || i == n - 1) {
if (!operators.empty()) {
// If the previous operator was '*' or '/', perform that operation
char prevOp = operators.top();
if (prevOp == '*' || prevOp == '/') {
operators.pop();
int prevNumber = numbers.top();
numbers.pop();
currentNumber = (prevOp == '*') ? prevNumber * currentNumber : prevNumber / currentNumber;
currentNumber = (prevOp == '*')
? prevNumber * currentNumber
: prevNumber / currentNumber;
} else if (prevOp == '-') {
operators.pop();
operators.push('+');
currentNumber = -currentNumber;
}
}
numbers.push(currentNumber);
Expand All @@ -59,22 +64,25 @@ int calculate(std::string s) {
}
}
}

// Now process remaining operators for addition or subtraction
int result = numbers.top();
numbers.pop();

if (operators.size() == 0)
return numbers.top();
int result = 0;
if (currentNumber != 0)
result = currentNumber;
else {
result = numbers.top();
numbers.pop();
}

while (!numbers.empty()) {
int first = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
int num = numbers.top();
numbers.pop();
if (op == '+') {
result += num;
} else if (op == '-') {
result = num - result;
}
result = (result + first);
}

return result;
}

Expand All @@ -87,7 +95,7 @@ int main() {

#### Complexity:
- **Time Complexity:** O(n), where n is the length of the string, since we are iterating once through the input.
- **Space Complexity:** O(n), due to the supplementary space used by two stacks.
- **Space Complexity:** O(n), due to the supplementary space used by four stacks.

---

Expand Down