数值的整数次方

题目

实现函数 double Power(double base, int exponent),求 base 的 exponent 次方。不得使用库函数,同时不需要考虑大数问题

解法

class Solution {
public:
    double Power(double b, int e) {
        bool flag=false;
        if(equal(b))
        {
            return 0.0;
        }

        int absE=e>0?e:-e;
        int res=powerCore(b,absE);
        return e>0?res:1.0/res;
    }
private:
    /*用于判定两个 double 型数据是否相等,不能直接用 == 只能用两者之间的差值在一个很小的范围内来判断*/  
    bool equal(double b)
    {
        if((b-0.0<0.000001)&&(b-0.0>-0.000001))
            return true;
        return false;
    }
    //考虑代码性能,如 2^16 = (2^8)^2 = ((2^4)^2)^2 ........等依次类推,这样减少了很多重复计算,因此改动 上面的代码的一部分
    int powerCore(double b,int e)
    {
        if(e==0)
            return 1;
        else if(e==1)
            return b;

        int res=powerCore(b,e>>1);
        res*=res;
        if(e&0x01)//判断是奇数次幂还是偶数次幂,用位运算移一位代表除以2,用与运算代替取余(%2)来判断是否是奇数。位运算效率更加高
            res*=b;
        return res;
    }
};

拓展

  1. 求a的n次方公式如下
        a^n/2*a^n/2
a^n=
        a^(n-1)/2*a(n-1)/2*a

   2.用位运算&左移一位代表除以2,用与运算代替取余(%2)来判断是否是奇数。位运算效率更加高

   3.用于判定两个 double 型数据是否相等,不能直接用 == 只能用两者之间的差值在一个很小的范围内来判断

原文地址:https://www.cnblogs.com/tianzeng/p/10146643.html