LeetCode 50. Pow(x, n)

LeetCode 50. Pow(x, n

    • Description
    • Example
    • Note
    • Code
    • Conclusion

Description

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

Example

LeetCode 50. Pow(x, n)_第1张图片

Note

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

Code

  • java
class Solution {
    // -1 -2147483648
    public double myPow(double x, int n) {
        if(n == Integer.MIN_VALUE) {
            if(Math.abs(Math.abs(x) - 1) < 1e-6) return 1;
            return 0;
        }
        double result = 1.0;
        boolean neg = n < 0 ? true : false;
        if(neg) n = -n;
        while(n != 0) {
            if((n & 1) == 1) result *= x;
            x *= x;
            n = n >> 1;
        }
        if(neg) result = 1.0 / result;
        return result;
    }
}
  • My Modified Solution
public class Solution {
    public double myPow(double x, int n) {
        if(n == Integer.MIN_VALUE) {
            if(Math.abs(Math.abs(x) - 1) < 1e-6) {
                return 1;
            }
            return 0;
        }
        double result = 1.0;
        if(n < 0) {
            x = 1.0 / x;
            n = -n;
        }
        while(n != 0) {
            if((n & 1) == 1) result *= x;
            x *= x;
            n >>= 1;
        }
        return result;
    }
}
  • Others’ Solution
public class Solution {
    public double myPow(double x, int n) {
        if(n<0) return 1/x * myPow(1/x, -(n+1));
        if(n==0) return 1;
        if(n==2) return x*x;
        if(n%2==0) return myPow( myPow(x, n/2), 2);
        else return x*myPow( myPow(x, n/2), 2);
    }
}

Conclusion

  • 注意负数的边界
  • 负数的时候计算换1.0 / x会快一些

你可能感兴趣的:(LeetCode,LeetCode,Pow)