
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.
1class Calculator:
2 def
In the Python solution, each method modifies self.result, a class attribute, and returns self to allow method chaining. The divide method checks for division by zero and raises a ValueError if encountered. The getResult() method returns the current result.
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.
1public class Calculator {
2 private double result;
3
4 public Calculator(double initialValue) {
5 this.result = initialValue;
6 }
7
8 public Calculator Add(double value) {
9 this.result += value;
10 return this;
11 }
12
13 public Calculator Subtract(double value) {
14 this.result -= value;
15 return this;
16 }
17
18 public Calculator Multiply(double value) {
19 this.result *= value;
20 return this;
21 }
22
23 public Calculator Divide(double value) {
24 if (value == 0) {
25 throw new DivideByZeroException("Division by zero is not allowed");
26 }
27 this.result /= value;
28 return this;
29 }
30
31 public Calculator Power(double value) {
32 this.result = Math.Pow(this.result, value);
33 return this;
34 }
35
36 public double GetResult() {
37 return this.result;
38 }
39}In C#, the calculator maintains a result field, with methods adjusting this field and returning the instance to facilitate method chaining. The Divide method handles division by zero using a DivideByZeroException. The use of Math.Pow handles exponentiation.