diff --git a/c++/basic-calculator-ii.md b/c++/basic-calculator-ii.md index 0c76c1d..d8fc5a0 100644 --- a/c++/basic-calculator-ii.md +++ b/c++/basic-calculator-ii.md @@ -31,25 +31,30 @@ int calculate(std::string s) { std::stack 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); @@ -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; } @@ -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. ---