50、Pow(x, n)

来源:互联网 发布:随身淘宝去异界书包网 编辑:程序博客网 时间:2024/05/19 07:10

Implement pow(xn).

Math Binary Search

double pow(double x, int n) {        double result = 1;        double fact = x;        //先把特殊情况排除掉       /* if (n == 0)            return 1;        if (x == 1 || x == 0)            return x;        if (x == -1)            return n % 2 == 0 ? 1 : -1;*/        if (n < 0)        {            fact = 1 / x;            result = fact;            n = -(n + 1);//防止最小负数        }               while (n)        {//下面的逻辑理解是此题解题关键            while (n % 2 == 0)            {                fact *= fact;                n /= 2;            }            result *= fact;            n -= 1;        }        return result;    }


0 0
原创粉丝点击