Implement pow(x, n), 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 】
代码:
1 class Solution { 2 public double myPow(double x, int n) { 3 if(n < 0) { 4 return 1.0 / power(x, -n); // 求倒 5 }else{ 6 return power(x, n); 7 } 8 } 9 10 private double power(double x, int n){ 11 if(n == 0) { 12 return 1; 13 } 14 double y = power(x, n / 2); 15 if( n % 2 ==0){ 16 return y*y; 17 }else{ 18 return y*y*x; 19 } 20 } 21 }