50. Pow(x, n)
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 23, 2024
Last updated : June 23, 2024
Related Topics : Math, Recursion
Acceptance Rate : 36.17 %
double myPowLong(double x, long n) {
if (n == 0)
return 1.;
if (n < 0)
return 1 / myPowLong(x, n * -1);
if (n == 1)
return x;
double half = myPowLong(x, n / 2);
long remainder = n % 2;
if (remainder == 1)
return half * half * x;
return half * half;
}
double myPow(double x, int n) {
return myPowLong(x, (long) n);
}
class Solution {
public double myPow(double x, int n) {
return myPow(x, (long) n);
}
private double myPow(double x, long n) {
if (n == 0)
return 1.;
if (n < 0)
return 1 / myPow(x, n * -1);
if (n == 1)
return x;
double half = myPow(x, n / 2);
long remainder = n % 2;
if (remainder == 1)
return half * half * x;
return half * half;
}
}
class Solution:
def myPow(self, x: float, n: int) -> float:
if not n :
return 1
if n == 1 :
return x
if n < 0 :
return 1 / self.myPow(x, -n)
half = n // 2
remainder = n - half * 2
half = self.myPow(x, half)
if remainder :
return x * half * half
return half * half