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 instancesubtract(value)- Subtracts the given number from the result and returns the Calculator instancemultiply(value)- Multiplies the result by the given number and returns the Calculator instancedivide(value)- Divides the result by the given number and returns the Calculator instance. Throws error "Division by zero is not allowed" if value is 0power(value)- Raises the result to the power of the given number and returns the Calculator instancegetResult()- 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code