← 返回 tesla 的题目列表Basic Calculator with Operators, Variables, and Functions
类型:qbank
Start from a Basic Calculator-style expression evaluator, then discuss extensions: exponentiation, parentheses, boolean operators, bitwise operators, variable declarations, and function declarations.
Requirements
Implement a Basic Calculator-style expression evaluator.
Extend the parser / evaluator to support more arithmetic operators, including exponentiation and parentheses.
Follow-ups may add boolean operators such as &&, ||, and not.
Follow-ups may add bitwise operators.
Later discussion moves into declarations: examples include a = 3, b = a + 3, a == b.
Final design discussion may add function declarations and calls, such as a = f(3) and func f(a) { a = a + 3 }.
Notes
Treat the prompt as a parser design ladder, not just a one-off stack calculator. A clean tokenizer plus precedence-based parser makes the follow-ups much easier than repeatedly patching ad hoc string logic.
For boolean and bitwise extensions, make precedence explicit before coding. The interviewer is likely probing whether the candidate can keep the grammar coherent as operators are added.
Exponentiation is usually right-associative, while arithmetic and most bitwise operators are left-associative. Put that rule in the precedence table before implementation so 2^3^2 and unary minus do not become accidental behavior.
Variable declarations require an environment map. Function declarations require scoped environments and an AST or equivalent representation; the later follow-ups can often be discussed without fully implementing them.
Preparation
Write a tokenizer and precedence-climbing parser for numbers, + - * / ^, unary operators, and parentheses; then add &&, ||, not, &, |, and == by editing only the precedence table.
Add a second pass with an environment map for assignments, then sketch how function definitions would capture parameters and local scope.
Test malformed input, whitespace, nested parentheses, right-associative exponentiation, and variable shadowing before optimizing.