Coding interviews
Reveal answer and reasoning
A batch can calculate every proposed total and checked aggregate into a private result before publishing it. That gives an all-or-error in-memory calculation boundary, while a real persistent commit still needs its own transaction. Define rounding once at the chosen unit conversion rather than applying inconsistent rounding independently to partial totals.
The arithmetic and validation are O(1) time and auxiliary storage for fixed-width inputs. Widening only after an int multiplication would be too late to repair overflow. Checked syntax must cover the actual multiplication inside the method; a checked caller context does not retroactively change unchecked arithmetic in another method. Using decimal does not remove the need for domain units, bounds or overflow handling.
Swallowing overflow and returning zero can turn invalid input into an apparently free order. An exception also needs a consistent API boundary so callers can distinguish invalid quantity from an unrepresentable accepted calculation.
A rigorous numeric answer identifies units, operand ranges, the type used during multiplication and the failure contract. It demonstrates both a valid widened product and rejection beyond the widened range. The associated checks should target zero, invalid signs and adjacent overflow boundaries. A senior review separates arithmetic safety from storage atomicity and payment replay behavior; neither follows from the checked keyword.
This lesson is deliberately small enough that every printed amount can be derived by hand, making a wrapped value or a too-late cast easy to distinguish from a correct implementation. Review the exact evaluation types in the expression tree: an explicit cast applied after multiplication cannot restore bits already discarded by a narrower operation.
What a strong answer covers
- A batch can calculate every proposed total and checked aggregate into a private result before publishing it.
- The arithmetic and validation are O(1) time and auxiliary storage for fixed-width inputs.
- Using decimal does not remove the need for domain units, bounds or overflow handling.
Common pitfall
Using decimal does not remove the need for domain units, bounds or overflow handling. Swallowing overflow and returning zero can turn invalid input into an apparently free order. An exception also needs a consistent API boundary so callers can distinguish invalid quantity from an unrepresentable accepted calculation.
Follow-up questions
- Test zero quantity, zero price, a negative operand and the largest representable successful product. Hint: derive the safe boundary by division before multiplication, while retaining checked arithmetic as the final guard.
- Where should rounding occur if prices arrive in fractional cents before aggregation?
Self-review
Choose what to revisit. These marks are your own assessment and are separate from lesson completion.