LeetCode-50. Pow(x,n)

Implement pow(x, n).

思路

利用递归求解。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public double myPow(double x, int n)
{
if(n == 0) return 1D;
long N = n; //use long to avoid overflow.
return solve(n < 0 ? (1 / x) : x, N < 0 ? (N * -1) : N);
}

public double solve(double x, long n)
{
if(n == 1) return x;
double val = solve(x, n / 2);
return val * val * ((n % 2) == 0 ? 1 : x);
}
-------------本文结束感谢您的阅读-------------
Thank you for your encouragement