MrainW's Home

All things come to those who wait!

0%

LeetCode 50. Pow(x, n)

Question

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
//time complexity logn
public double myPow(double x, int n) {
if ( x == 0 || x == 1) return x;
if (n < 0) return 1 / pow(x, -n);
return pow(x, n);
}
private double pow(double x, int n){
if (n == 0) return 1;
double y = pow(x, n / 2);
if (n % 2 == 0) return y * y;
else return y * y * x;
}
}

Complexity:

Time complexity: O( logn)

Space complexity: O(logn)

Welcome to my other publishing channels