Practice/Microsoft/Leetcode 2726. Calculator with Method Chaining
CodingMust
Design and implement a FluentCalculator class that enables chained mathematical operations through a fluent interface pattern. The calculator should maintain an internal state representing the current calculated value and allow multiple operations to be performed in sequence by returning the calculator instance itself from each operation method.
The class must support the following operations: addition, subtraction, multiplication, division, and exponentiation (power). Each operation should modify the internal state and return the calculator object to enable method chaining. A final method should retrieve the computed result.
add(value) method that adds the given value to the current resultsubtract(value) method that subtracts the given value from the current resultmultiply(value) method that multiplies the current result by the given valuedivide(value) method that divides the current result by the given valuedivide method must throw an exception with the message "Division by zero is not allowed" when the divisor is 0power(value) method that raises the current result to the given exponentget_result() method that returns the final calculated valueExample 1:
Input: FluentCalculator(10).add(5).subtract(3).get_result() Output: 12 Explanation: Start with 10, add 5 to get 15, subtract 3 to get 12
Example 2:
Input: FluentCalculator(2).multiply(3).power(2).get_result() Output: 36 Explanation: Start with 2, multiply by 3 to get 6, raise to power 2 to get 36
Example 3:
Input: FluentCalculator(100).divide(4).add(10).multiply(2).get_result() Output: 70 Explanation: Start with 100, divide by 4 to get 25, add 10 to get 35, multiply by 2 to get 70
Example 4:
Input: FluentCalculator(5).divide(0) Output: Exception raised Explanation: Attempting to divide by zero throws an exception