[leetcode]50. Pow(x, n)求幂

时间:2023-03-08 17:45:15

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

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

题意:

求幂

思路:

指数n 大于0 返回  power(x, n)

小于0  返回  1.0 / power(x, -n) 【容易漏掉】

等于0  返回 1

不断通过除2来裂变n

n % 2 ==0, 返回  y*y

n % 2 !=0, 返回  y*y*x  【比如25= 22 * 22 * 2 】

代码:

 class Solution {
public double myPow(double x, int n) {
if(n < 0) {
return 1.0 / power(x, -n); // 求倒
}else{
return power(x, n);
}
} private double power(double x, int n){
if(n == 0) {
return 1;
}
double y = power(x, n / 2);
if( n % 2 ==0){
return y*y;
}else{
return y*y*x;
}
}
}