[LintCode] Pow(x, n) [Binary Search]

460 查看

Problem

Implement pow(x, n).

Example

Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1

Note

You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3.

Challenge

O(logn) time

Solution

When you see O(logn) time for a obvious O(n) time question, think about binary search and recursion.

Double myPow()

无须考虑n为Integer.MIN_VALUE的情况,直接转化成正数计算倒数。

public class Solution {
    public double myPow(double x, int n) {
        if (n < 0) return 1/pow(x, -n);
        else return pow(x, n);
    }
    private double pow(double x, int n) {
        if (n == 0) return 1;
        double val = pow(x, n/2);
        if (n % 2 == 0) return val*val;
        else return val*val*x;
    }
}

Double x

需要注意n = Integer.MIN_VALUE的情况,取负数之后会溢出。

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