剑指offer之数组的整数N次方

题目:

实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
题目链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof

//判断双精度整数0是一个范围值
int equal(double x,double y)
{
    if((x-y>-0.000001)&&(x-y<0.000001))
        {
            return 1;
        }
        else
        {
            return 0;
        }
}


//快速求解x的n次幂
//x^n=x^(n/2)*x^(n/2)  n为偶数
//x^n=x^[(n-1)/2]*x^[(n-1)/2]*x
double DoublePow(double x, unsigned long n)
{
    if(n==0)
    return 1;
    if(n==1)
    return x;
    double ret=DoublePow(x,n>>1);
    ret*=ret;
    if(n&0x1==1)
    ret*=x;
    return ret;
}
double myPow(double x, int n){
    
    if(equal(x,0.0)==1&&n<0)
    return 0.0;
    unsigned long  abs_n=(unsigned long)  n;
    
      if(n<0)
        abs_n= -abs_n;
    
    double ret=DoublePow(x,abs_n);
    if(n<0)
    ret=1.0/ret;
    return ret;
}
发布了24 篇原创文章 · 获赞 1 · 访问量 374

猜你喜欢

转载自blog.csdn.net/weixin_43519514/article/details/104780164