#2726
Calculator with Method Chaining
EasyMethod ChainingError Handling
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(1) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution is similar to the brute force approach but emphasizes clarity and efficiency in method chaining. Each method modifies the state of the object and returns the same instance, allowing for seamless chaining of operations.
⚙️
Algorithm
3 steps- 1Step 1: Define the Calculator class with an initial result.
- 2Step 2: Implement methods for each operation that update the result and return 'this'.
- 3Step 3: Ensure error handling for division by zero.
solution.py28 lines
1class Calculator:
2 def __init__(self, value):
3 self.result = value
4
5 def add(self, value):
6 self.result += value
7 return self
8
9 def subtract(self, value):
10 self.result -= value
11 return self
12
13 def multiply(self, value):
14 self.result *= value
15 return self
16
17 def divide(self, value):
18 if value == 0:
19 raise ValueError('Division by zero is not allowed')
20 self.result /= value
21 return self
22
23 def power(self, value):
24 self.result **= value
25 return self
26
27 def getResult(self):
28 return self.resultℹ
Complexity note: Each operation is performed in constant time since we are only updating a single variable (result).
- 1Method chaining allows for cleaner and more readable code.
- 2Error handling is crucial for operations like division.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.