Evaluate Parenthesized Integer Arithmetic

Quick Overview

Evaluate Parenthesized Integer Arithmetic. Evaluate the valid arithmetic string s containing nonnegative integer tokens, +, -, *, / and parentheses.

Evaluate Parenthesized Integer Arithmetic

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Evaluate the valid arithmetic string s containing nonnegative integer tokens, +, -, *, / and parentheses. Apply ordinary precedence, grouping and left associativity; integer division truncates toward zero. Do not use a built-in expression evaluator. All arithmetic intermediates fit signed 32-bit integers. ```cpp class Solution { public: int calculate(string s); }; ``` ### Examples **Example 1:** ```text s = "3*(8-5)+10/4" Output: 11 Explanation: 3*3+2=11 after truncating 10/4. ``` **Example 2:** ```text s = "(2-9)/2" Output: -3 Explanation: -7/2 truncates toward zero. ``` ### Constraints - **Input-length clarification:** The string contains 1 through 10000 characters. - Input characters are digits, +, -, *, / and parentheses, and the expression is valid. - Every arithmetic intermediate belongs to [-2147483648,2147483647]. ### Contract considerations Respect operator precedence and truncate division toward zero. Do not use a built-in expression evaluator. ```hint Read the boundary condition Which parsing level should handle multiplication before addition? ``` ### Boundary reminders Respect operator precedence and truncate division toward zero. Do not use a built-in expression evaluator.

Overview: Evaluate Parenthesized Integer Arithmetic. Evaluate the valid arithmetic string s containing nonnegative integer tokens, +, -, *, / and parentheses.

Google logo
Google
Source window: 0–6 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Evaluate the valid arithmetic string s containing nonnegative integer tokens, +, -, *, / and parentheses. Apply ordinary precedence, grouping and left associativity; integer division truncates toward zero. Do not use a built-in expression evaluator. All arithmetic intermediates fit signed 32-bit integers.

class Solution {
public:
    int calculate(string s);
};

Examples

Example 1:

s = "3*(8-5)+10/4"
Output: 11
Explanation: 3*3+2=11 after truncating 10/4.

Example 2:

s = "(2-9)/2"
Output: -3
Explanation: -7/2 truncates toward zero.

Constraints

  • Input-length clarification: The string contains 1 through 10000 characters.
  • Input characters are digits, +, -, *, / and parentheses, and the expression is valid.
  • Every arithmetic intermediate belongs to [-2147483648,2147483647].

Contract considerations

Respect operator precedence and truncate division toward zero. Do not use a built-in expression evaluator.

Boundary reminders

Respect operator precedence and truncate division toward zero. Do not use a built-in expression evaluator.