50. Pow(x, n)

来源:互联网 发布:windows 98 iso 编辑:程序博客网 时间:2024/05/29 23:24

采用递归的方法,将Pow(x,n),转化为Pow(x,n/2)*Pow(x,n/2)。

将时间从O(n)变成O(logn)关键是写出边界条件。并注意定义double类型的tmp=pow(x,n/2).对n的正负以及奇偶做判断。

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