LeetCode 2726: Calculator with Method Chaining Solution
Master LeetCode problem 2726 (Calculator with Method Chaining), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2726. Calculator with Method Chaining
Problem Explanation
Explanation
To solve this problem, we need to implement a Calculator class with methods for addition, subtraction, multiplication, division, exponentiation, and getResult. The key aspect is to allow method chaining, where each method returns the updated Calculator instance to enable consecutive operations.
We will maintain a variable result to store the current calculated result. Each method will update this result based on the operation performed and return the Calculator instance itself for method chaining.
The divide method needs to handle the special case where the divisor is 0 by throwing an error message.
Solution Code
class Calculator {
private double result;
public Calculator(double initialValue) {
this.result = initialValue;
}
public Calculator add(double num) {
this.result += num;
return this;
}
public Calculator subtract(double num) {
this.result -= num;
return this;
}
public Calculator multiply(double num) {
this.result *= num;
return this;
}
public Calculator divide(double num) {
if (num == 0) {
throw new IllegalArgumentException("Division by zero is not allowed");
}
this.result /= num;
return this;
}
public Calculator power(double num) {
this.result = Math.pow(this.result, num);
return this;
}
public double getResult() {
return this.result;
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2726 (Calculator with Method Chaining)?
This page provides optimized solutions for LeetCode problem 2726 (Calculator with Method Chaining) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2726 (Calculator with Method Chaining)?
The time complexity for LeetCode 2726 (Calculator with Method Chaining) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2726 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2726 in Java, C++, or Python.