50. Pow(x, n)

https://leetcode.com/problems/powx-n/description/

一道无聊的二分。注意 n 为 Integer.MIN_VALUE的情况,-n 为 0.

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

你可能感兴趣的:(50. Pow(x, n))