50. Pow(x, n)
Explanation:
To calculate x raised to the power of n, we can use the concept of exponentiation by squaring. The idea is to break down the problem into smaller subproblems by dividing the power n by 2 in each step. By recursively solving these subproblems, we can efficiently compute the result. If n is even, we can square the result of x raised to the power of n/2. If n is odd, we need to multiply the result of x raised to the power of n/2 with itself and x. This approach optimizes the number of multiplications required.
Algorithm:
- If n is 0, return 1.
- If n is negative, update x to 1/x and n to -n to handle negative exponents.
- Initialize a variable result to 1.
- Loop while n is greater than 0:
- If n is odd, multiply result by x.
- Update x to x squared.
- Divide n by 2.
- Return result.
Time Complexity:
The time complexity of this algorithm is O(log n) as we are reducing the problem size by half in each step.
Space Complexity:
The space complexity is O(1) as we are using a constant amount of extra space.
: :
class Solution {
public double myPow(double x, int n) {
if (n == 0) return 1;
if (n < 0) {
x = 1 / x;
n = -n;
}
double result = 1;
while (n > 0) {
if (n % 2 == 1) {
result *= x;
}
x *= x;
n /= 2;
}
return result;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.