Problem Description
Design a Calculator class that supports the basic arithmetic operations of addition, subtraction, multiplication, division, and exponentiation. It should be possible to chain the operations. The class constructor accepts an initial number which becomes the starting result. Each method (except getResult) performs the operation, updates the result, and then returns the Calculator object to enable method chaining. Notably, division by zero should trigger an error with the message "Division by zero is not allowed". The getResult method returns the current result.
Key Insights
- Use method chaining by returning the same instance (self or this) from each arithmetic method.
- Properly handle division by zero by throwing an error/exception.
- Ensure that each arithmetic operation updates the internal state of the Calculator.
- The solution is straightforward as it only requires handling basic arithmetic operations and chaining them.
Space and Time Complexity
Time Complexity: O(1) per method call (each operation is computed in constant time). Space Complexity: O(1), only a few variables are used regardless of input size.
Solution
We design a Calculator class by declaring an instance variable to hold the current result. Each arithmetic method performs the related operation, updates the result, and then returns the Calculator instance itself to allow for method chaining. In the case of division, before performing the division, we check if the divisor is zero; if it is, an error with a specific message is thrown. This design meets the requirements of chaining since each operation returns the same Calculator object. Data structure used is a simple object encapsulating a number as its state, and all operations are executed in constant time.