【题目】

多次方计算,主要是正负两种情况

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

 

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

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

 

【思路】

  • 分类讨论正负两种情况即可
  • 将负数也全部转换为正数计算,即x^-1=1/x
  • 避免负数时 2.00000 -2147483648溢出

【代码】

class Solution {
    public double myPow(double x, int n) {
        if(n == 0)
            return 1;
        if(n<0){
            return 1/x * myPow(1/x, -(n + 1));
            //1/x 因为x^-1=1/x 
            //-(n+1)变成正数处理,把负数给x了
        }
        return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
    }
}

 

 posted on 2021-08-19 13:27  alau  阅读(23)  评论(0编辑  收藏  举报