LeetCode 50. Pow(x, n) Pow(x, n)(Java)

题目:

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

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]

解答:

错误解法
看到题目只有常规暴力解法的思路,即根据幂的正负进行分情况讨论,若幂为正数则迭代相乘后返回结果;若为负数则返回结果的倒数。但提交结果显示超时。

class Solution {
    public double myPow(double x, int n) {
        double res = 1.0;
        if(n==0) {
            return 1.0;
        }
        if(n<0) {
            while(n!=0) {
                res *= x;
                n++;
            }
            return 1/res;
        } else {
            while(n!=0) {
                res *=x;
                n--;
            }
        }
        return res;
    }
}

提交错误:Time Limit Exceeded
在这里插入图片描述
为避免溢出,应该采用递归或者循环的方式

解法一:递归

计算 x 的 n 次幂,采用递归的话,应该分为两种情况:
如果 n 为偶数,则 y = x n = ( x n 2 ) 2 y = x^n =(x^\frac {n} {2})^2 y=xn=(x2n)2
如果 n 为奇数,则 y = x n = ( x n − 1 2 ) 2 ∗ x y = x^n =(x^\frac {n-1} {2})^2*x y=xn=(x2n1)2x

如果 n<0,把 n 变成 -n 进行计算,并将最终结果变成 1/res

其中要注意,若n = -2^31,(int的取值范围为-2147483648~2147483647), 那么取反后 n 是超出 int 范围的,所以需要进行特殊处理。

class Solution {
    public double myPow(double x, int n) {
        if(n == 0) {
            return 1;
        }
        if(n == Integer.MIN_VALUE) {
            return 1/x*myPow(x, n+1);
        }
        if(n<0) {
            n=-n;
            x=1/x;
        }
        return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
    }
}

解法二:循环

可以采用相同的思路,将递归改为循环的方式,让 i 初始化为 n,然后看 i 是否是2的倍数,是的话 x 乘以自己,否则 res 乘以 x,i 每次循环都缩小一半,直到为0时停止循环

class Solution {
    public double myPow(double x, int n) {
        double res = 1.0;
        for(int i=n; i!=0; i/=2) {
            if(i%2 !=0) {
                res *= x; 
            }
            x *= x;
        }
        return (n>0) ? res : 1/res;
    }
}

你可能感兴趣的:(LeetCode)