*[Lintcode]Pow(x, n)

来源:互联网 发布:mac卸载win10 编辑:程序博客网 时间:2024/06/05 23:01

Implement pow(x, n).


Example

Pow(2.1, 3) = 9.261Pow(0, 1) = 0Pow(1, 0) = 1
分析:首先是O(n)解法
<pre name="code" class="java">public class Solution {    /**     * @param x the base number     * @param n the power number     * @return the result     */    public double myPow(double x, int n) {        if(x == 0.0) return 0;        if(n == 0) return 1;        if(n == 1) return x;                double res = x;        int newN = n;        if(n < 0) newN *= -1;        while(newN > 1) {            res *= x;            newN--;        }        return n < 0 ? 1/res :res;    }}


O(logN)解法 :看到这个复杂度首先考虑二分法。
<pre name="code" class="java">public class Solution {    /**     * @param x the base number     * @param n the power number     * @return the result     */    public double myPow(double x, int n) {        if(x == 0.0) return 0;        if(n == 0) return 1;        if(n == 1) return x;                if(n < 0) return 1 / myPow(x, -n);        double half = myPow(x, n / 2);        if(n % 2 == 0) return half * half;        else return half * half * x;    }}


0 0
原创粉丝点击