
Sponsored
Sponsored
In this approach, we will design a Calculator class with a constructor that initializes the result. Each operation method will modify the object's state and return the Calculator object itself to allow method chaining. The method for division needs to handle division by zero gracefully by throwing an appropriate exception.
Time Complexity: O(1) for each operation since they all perform a constant amount of work.
Space Complexity: O(1) since we use only a fixed amount of space irrespective of input size.
1public class Calculator {
2
In the Java solution, we maintain a result field. Each method updates this field and returns this to make method chaining possible. The divide method checks for division by zero and throws an ArithmeticException if necessary. The class utilizes Math.pow for exponentiation.
This approach emphasizes clear error management alongside method chaining. Each mathematical function adjusts the internal result and returns the instance for seamless operation chaining. Special attention is paid to division, where an exception is thrown in case of dividing by zero, ensuring the program handles this gracefully.
Time Complexity: O(1) for each operation; each involves direct arithmetic with a constant time overhead.
Space Complexity: O(1) due to constant space usage regardless of input size.
1class Calculator {
2 constructor(initialValue) {
3 this.result = initialValue;
4 }
5
6 add(value) {
7 this.result += value;
8 return this;
9 }
10
11 subtract(value) {
12 this.result -= value;
13 return this;
14 }
15
16 multiply(value) {
17 this.result *= value;
18 return this;
19 }
20
21 divide(value) {
22 if (value === 0) {
23 throw new Error("Division by zero is not allowed");
24 }
25 this.result /= value;
26 return this;
27 }
28
29 power(value) {
30 this.result **= value;
31 return this;
32 }
33
34 getResult() {
35 return this.result;
36 }
37}In the JavaScript implementation, each operation method updates the result attribute and returns the current instance to enable method chaining. The divide method checks for zero to prevent division by zero, throwing an Error as appropriate. The method getResult retrieves the current value of result.