Design a Calculator class. The class should provide theĀ mathematical operations ofĀ addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining.Ā The Calculator class constructor should accept a numberĀ which serves as theĀ initial value of result.
Your CalculatorĀ class should have the following methods:
add - This method adds the given number value to theĀ result and returns the updated Calculator.subtract -Ā This method subtracts the given number valueĀ from theĀ result and returns the updated Calculator.multiply -Ā This method multiplies the resultĀ by the given number value and returns the updated Calculator.divide -Ā This method divides the result by the given number value and returns the updated Calculator. If the passed value is 0, an error "Division by zero is not allowed" should be thrown.power -Ā This method raises theĀ result to the power of the given number value and returns the updated Calculator.getResult -Ā This method returns the result.Solutions withinĀ 10-5Ā of the actual result are considered correct.
Example 1:
Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] Output: 8 Explanation: new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8
Example 2:
Input: actions = ["Calculator", "multiply", "power", "getResult"], values = [2, 5, 2] Output: 100 Explanation: new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100
Example 3:
Input: actions = ["Calculator", "divide", "getResult"], values = [20, 0] Output: "Division by zero is not allowed" Explanation: new Calculator(20).divide(0).getResult() // 20 / 0 The error should be thrown because we cannot divide by zero.
Constraints:
actions is a valid JSON array of stringsvaluesĀ is a valid JSON array of numbers2 <= actions.length <= 2 * 1041 <= values.length <= 2 * 104Ā - 1actions[i] is one of "Calculator", "add", "subtract", "multiply", "divide", "power", andĀ "getResult"["Calculator", "add", "subtract", "getResult"] [10, 5, 7]
["Calculator", "multiply", "power", "getResult"] [2, 5, 2]
["Calculator", "divide", "getResult"] [20, 0]