Problem Description
Design a Calculator
class that provides mathematical operations of addition, subtraction, multiplication, division, and exponentiation, allowing for method chaining. The constructor accepts an initial value for result
.
Key Insights
- The
Calculator
class should support method chaining, meaning each operation returns the instance itself. - Proper error handling must be implemented for division by zero.
- The result should be returned with a precision of up to 10^-5.
Space and Time Complexity
Time Complexity: O(1) for each operation since they involve basic arithmetic. Space Complexity: O(1) as we are only storing a single result value.
Solution
The solution involves creating a Calculator
class that maintains an internal result
variable, initialized in the constructor. Each mathematical operation (add, subtract, multiply, divide, power) modifies this result
and then returns the instance of the Calculator
to allow for chaining. The getResult
method retrieves the current value of result
. Error handling is implemented specifically for division to prevent division by zero.