Pow(x, n)

来源:互联网 发布:淘宝店铺售假24分重开 编辑:程序博客网 时间:2024/05/20 22:28

一、问题描述

二、思路

开始想到算法导论时学过的二分法,即利用奇偶性求解。

公式:

n为偶数:result = x ^N/2 * x^N/2;

n为奇数:result = x ^N/2 * x^N/2  * x;

三、代码

double myPow(double x, int n) {    double res=1;    x = n>=0?x:1/x;    unsigned int nl = abs(n);    while(nl){        if (nl&1) res*=x;        nl>>=1;        x*=x;    }    return res;}


0 0