We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Calculator with Method Chaining

Number: 2863

Difficulty: Easy

Paid? No

Companies: N/A


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.


Code Solutions

# Python implementation of the Calculator class with method chaining.
class Calculator:
    def __init__(self, initial_value):
        # Set the initial result value
        self.result = initial_value
        
    def add(self, value):
        # Add the provided value to the result.
        self.result += value
        return self  # Return self to enable chaining.
        
    def subtract(self, value):
        # Subtract the provided value from the result.
        self.result -= value
        return self
        
    def multiply(self, value):
        # Multiply the result by the provided value.
        self.result *= value
        return self
        
    def divide(self, value):
        # If the division value is zero, raise an Exception.
        if value == 0:
            raise Exception("Division by zero is not allowed")
        self.result /= value
        return self
        
    def power(self, value):
        # Raise the result to the power of the provided value.
        self.result **= value
        return self
        
    def getResult(self):
        # Return the current result.
        return self.result

# Example usage:
# new Calculator(10).add(5).subtract(7).getResult() returns 8
← Back to All Questions