Junior · Explain · Numeric correctness

Why must widening and checked arithmetic occur at the actual billing multiplication, and which failures remain distinct?

Think through your answer before opening the explanation.

Coding interviews

Reveal answer and reasoning

Compute a nonnegative quantity times a nonnegative price expressed in integer cents. The result is a checked long, zero quantity is valid and an unrepresentable total is rejected with OverflowException. The task avoids floating-point currency rounding by defining integer units, but taxes, fractional pricing and currency conversion remain separate business rules. State whether invalid operands, unrepresentable totals and zero-value orders are different outcomes.

Here negatives are argument errors, arithmetic overflow is exceptional and zero quantity returns zero. Integer cents make the unit precise, but they do not establish rules for currencies whose minor units or rounding requirements differ.

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. A fixed-width multiplication has constant algorithmic cost, while parsing arbitrary-length numeric input or using arbitrary-precision arithmetic would have another model.

The sample neither parses money text nor formats a currency. Keeping calculation and representation separate makes both the overflow proof and deterministic output easier to inspect.

What a strong answer covers

  • Compute a nonnegative quantity times a nonnegative price expressed in integer cents.
  • The wide-product fixture is intentionally larger than int.MaxValue but still valid as long.
  • The arithmetic and validation are O(1) time and auxiliary storage for fixed-width inputs.

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

  1. 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.
  2. 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.

Primary references

Open lesson and code ↗

← All interview questions