Pow(x, n)

来源:互联网 发布:什么是网络公关 编辑:程序博客网 时间:2024/06/05 03:33

最朴素的想法会超时,当n特别大的时候。

pow(x,n)就是求x的n次方。x的N次方可以看做:x^n = x^(n/2)*x^(n/2)*x^(n%2)。所以利用递归求解,当n==0,返回1。

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 v = pow(x, n/2);        if (n % 2 ==0) {            x = v*v;        } else {            x = v*v*x;        }        return x;    }            // public double myPow(double x, int n) {    //     if (n == 0) {    //         return 1;    //     }    //     if (n == 1) {    //         return x;    //     }    //     boolean flag = false;    //     if (n < 0) {    //         flag = true;    //         n = -n;    //     }    //     double y = x;    //     for (int i = 1; i < n; i++) {    //         x = y*x;    //     }    //     if (flag) {    //         return 1/x;    //     } else     //     return x;    // }}



0 0
原创粉丝点击