medium Basic Calculator II
Problem Statement
Given a string s, representing the mathematical expression, evaluate the expression and return the integer value.
The integer division should truncate toward zero.
*Note: You are not allowed to use the built-in functions like eval().
Examples
Example 1:
- Input:
"8*5/4+3-2" - Expected Output:
11 - Justification: The calculation proceeds as follows:
8*5 = 40,40/4 = 10,10+3 = 13,13-2 = 11.
Example 2:
- Input:
"10+20/5*3" - Expected Output:
22 - Justification: The order of operations gives
20/5 = 4,4*3 = 12, and10+12 = 22.
Example 3:
- Input:
"50-25+5*3/2*2-10/2" - Expected Output:
34 - Justification: Following the order of operations:
50 - 25 = 25,(15/2) = 7(rounded down),7*2 = 14,25+14 = 39,10/2 = 5, and39 - 5 = 34.
Try it yourself
Try solving this question here:
✅ Solution Basic Calculator II
Problem Statement
Given a string s, representing the mathematical expression, evaluate the expression and return the integer value.
The integer division should truncate toward zero.
*Note: You are not allowed to use the built-in functions like eval().
Examples
Example 1:
- Input:
"8*5/4+3-2" - Expected Output:
11 - Justification: The calculation proceeds as follows:
8*5 = 40,40/4 = 10,10+3 = 13,13-2 = 11.
Example 2:
- Input:
"10+20/5*3" - Expected Output:
22 - Justification: The order of operations gives
20/5 = 4,4*3 = 12, and10+12 = 22.
Example 3:
- Input:
"50-25+5*3/2*2-10/2" - Expected Output:
34 - Justification: Following the order of operations:
50 - 25 = 25,(15/2) = 7(rounded down),7*2 = 14,25+14 = 39,10/2 = 5, and39 - 5 = 34.
Solution
To solve this problem, our approach blends linear parsing with immediate evaluation of arithmetic operations. This methodology effectively addresses the challenge of respecting the standard order of operations (multiplication and division prior to addition and subtraction) within a single pass through the expression. The logic behind this approach is to evaluate and accumulate partial results as soon as possible, especially when dealing with multiplication and division, which have higher precedence.
The efficiency of this method lies in its ability to process the expression in a single sweep, thereby minimizing the need for backtracking or re-evaluating portions of the expression. By updating the cumulative result and the last evaluated number at each step, based on the current operation, the algorithm ensures that the most recent operation is always applied correctly. This real-time processing approach not only maintains the correct order of operations but also streamlines the computational process, leading to a solution that is both time and space-efficient.
Step-by-Step Algorithm
- Initialize
currentNumber,lastNumber, andresultto 0, and setoperationto '+'. - Iterate over each character in the input string:
- If the character is a digit, update
currentNumberaccordingly. - If the character is a non-digit, non-space, or it's the end of the string:
- If
operationis '+' or '-', addlastNumbertoresult. UpdatelastNumbertocurrentNumberor-currentNumberbased onoperation. - If
operationis '*', multiplylastNumberwithcurrentNumber. - If
operationis '/', dividelastNumberbycurrentNumber. - Update
operationto the current character. - Reset
currentNumberto 0.
- If
- If the character is a digit, update
- After the loop, add
lastNumbertoresultfor the final total.
Algorithm Walkthrough
let's consider input: "50-25+5*3/2*2-10/2"
Certainly, let's correct the walkthrough of the code with the input "50-25+5*3/2*2-10/2". We'll carefully trace through the arithmetic and ensure accurate computation at each step.
-
Initialization:
currentNumber = 0,lastNumber = 0,result = 0,operation = '+'.
-
Processing each character:
- Iterate through each character of the string.
-
First Character '5':
currentNumberbecomes 5.
-
Second Character '0':
currentNumberbecomes 50.
-
Third Character '-':
- Operation is
+, solastNumber = 50(ascurrentNumberis 50). resultbecomes 0 (0 + 0).operationupdated to '-'.currentNumberreset to 0.
- Operation is
-
Next Characters '25':
currentNumberbecomes 25.
-
Character '+':
- Operation is '-', so
lastNumber = -25. resultbecomes 50 (0 + 50).operationupdated to '+'.currentNumberreset to 0.
- Operation is '-', so
-
Next Characters '5':
currentNumberbecomes 5.
-
Character '*':
- Operation is '+',
resultbecomes 25 (50 - 25). - Update `lastNumber = 5
operationupdated to '*'.currentNumberreset to 0.
- Operation is '+',
-
Next Characters '3':
currentNumberbecomes 3.
-
Character '/':
- Operation is '*', so
lastNumberbecomes 15 (5 * 3). operationupdated to '/'.currentNumberreset to 0.
- Operation is '*', so
-
Next Characters '2':
currentNumberbecomes 2.
-
Character '*':
- Operation is '/', so
lastNumberbecomes 7 (15 / 2, rounded down for integer division). operationupdated to '*'.currentNumberreset to 0.
- Operation is '/', so
-
Next Characters '2':
currentNumberbecomes 2.
-
Character '-':
- Operation is '*', so
lastNumberbecomes 14 (7 * 2). resultbecomes 39 (25 + 14).operationupdated to '-'.currentNumberreset to 0.
- Operation is '*', so
-
Next Characters '10':
currentNumberbecomes 10.
-
Character '/':
- Operation is '-', so
lastNumberbecomes -10. resultremains 39.operationupdated to '/'.currentNumberreset to 0.
- Operation is '-', so
-
Next Characters '2':
currentNumberbecomes 2.
-
End of String:
- Operation is '/', so
lastNumberbecomes -5 (10 / 2, integer division). resultbecomes 34 (39 - 5).
- Operation is '/', so
-
Final Calculation:
resultis 34.
Code
public class Solution {
public int calculate(String s) {
if (s == null || s.isEmpty()) return 0;
int currentNumber = 0, lastNumber = 0, result = 0;
char operation = '+';
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
// Building the current number if it's a digit
if (Character.isDigit(currentChar)) {
currentNumber = (currentNumber * 10) + (currentChar - '0');
}
// Performing calculation upon encountering an operator or at the end of the string
if (
(!Character.isDigit(currentChar) &&
!Character.isWhitespace(currentChar)) ||
i == s.length() - 1
) {
if (operation == '+' || operation == '-') {
// For '+' and '-', add lastNumber to result and update lastNumber
result += lastNumber;
lastNumber = (operation == '+') ? currentNumber : -currentNumber;
} else if (operation == '*') {
// For '*', multiply lastNumber with currentNumber
lastNumber *= currentNumber;
} else if (operation == '/') {
// For '/', divide lastNumber by currentNumber
lastNumber /= currentNumber;
}
operation = currentChar; // Update the operation
currentNumber = 0; // Reset currentNumber
}
}
result += lastNumber; // Add the last number to result
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.calculate("50-25+5*3/2*2-10/2")); // Example test case
}
}
Complexity Analysis
-
Time Complexity: The algorithm has a linear time complexity of
O(N), where N represents the length of the input string. This is because the algorithm processes each character in the string exactly once. -
Space Complexity: The space complexity of the algorithm is
O(1), or constant space complexity. This is due to the use of a fixed number of variables regardless of the size of the input string.
🤖 Don't fully get this? Learn it with Claude
Stuck on Basic Calculator II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Basic Calculator II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Basic Calculator II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Basic Calculator II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Basic Calculator II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.