Calculator with Method Chaining - Problem

Design a Calculator class that provides mathematical operations with method chaining support. The class should allow consecutive operations to be performed in a fluent interface style.

The Calculator constructor accepts an initial number which serves as the starting value for calculations.

Required Methods:

  • add(value) - Adds the given number to the result and returns the Calculator instance
  • subtract(value) - Subtracts the given number from the result and returns the Calculator instance
  • multiply(value) - Multiplies the result by the given number and returns the Calculator instance
  • divide(value) - Divides the result by the given number and returns the Calculator instance. Throws error "Division by zero is not allowed" if value is 0
  • power(value) - Raises the result to the power of the given number and returns the Calculator instance
  • getResult() - Returns the current result as a number

Solutions within 10⁻⁵ of the actual result are considered correct.

Input & Output

Example 1 — Basic Chaining
$ Input: Calculator(10).add(5).multiply(2).getResult()
Output: 30
💡 Note: Start with 10, add 5 to get 15, multiply by 2 to get 30
Example 2 — Power Operation
$ Input: Calculator(2).power(3).subtract(3).getResult()
Output: 5
💡 Note: Start with 2, raise to power 3 to get 8, subtract 3 to get 5
Example 3 — Division Error
$ Input: Calculator(10).divide(0)
Output: Error: Division by zero is not allowed
💡 Note: Division by zero throws an error as specified

Constraints

  • -1000 ≤ initial value ≤ 1000
  • -100 ≤ operation values ≤ 100
  • 1 ≤ number of operations ≤ 10
  • Division by zero throws error

Visualization

Tap to expand
Calculator Method Chaining: Fluent Interface PatternInputinitial: 10add(5) → thismultiply(2) → thisgetResult() → 30Calculatorresult: 10↓ add(5)result: 15Output30calc(10).add(5).multiply(2).getResult()Each method returns this to enable chaining
Understanding the Visualization
1
Input
Initial value and sequence of operations
2
Process
Each method modifies result and returns this
3
Output
Final calculated result
Key Takeaway
🎯 Key Insight: Return 'this' from each method to create a fluent interface that allows natural method chaining
Asked in
Google 25 Amazon 18 Microsoft 15
24.1K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen