Wednesday, July 23, 2014

Pow(x, n)

Implement pow(x, n).

二分法,注意n = 1和0的特殊情况
public class Solution {
    //Time: O(logn)
    public double pow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        
        boolean isNeg = false;
        if (n < 0) {
            n = -n;
            isNeg = true;
        }
        
        double half = pow(x, n / 2);
        if (n % 2 == 0) {
            return isNeg ? 1 / (half * half) : half * half;
        } else {
            return isNeg ? 1 / (half * half * x) : half * half * x;
        }
    }
}

No comments:

Post a Comment