剑指offer-面试题16-数值的整数次方-数字

/*
题目:
	实现函数double Power(double base,int exponent),
	求base的exponent次方。
*/
/*
思路:
	本题需要考虑的情况较多:
		1、0的负数次方报错。
		2、判断double值为0,需要使用精度。
		3、考虑exponent为负数的情况。
	可创新的点:
		求x(n次方),可用x(n/2次方)*2(n/2次方) x为偶数
		求x(n次方),可用x(n/2次方)*2(n/2次方)*x x为奇数
*/
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cmath>
using namespace std;
#define MIN_VALUE 1e-8

bool g_InvalidInput = false;

bool equal0(double num1){
    if(abs(num1) < MIN_VALUE) return true;
    return false;
}
double PowerWithUnsignedExponent(double base,unsigned int exponent){
    if(exponent == 0){
        return 1;
    }
    if(exponent == 1){
        return base;
    }
	//用位运算代替除法
    double result = PowerWithUnsignedExponent(base,exponent >>1 );
    result *= result;
	//判断exponent为奇数时,需要多乘一次。
	//用位运算代替取模
    if(exponent &0x1 == 1){
        result *= base;
    }
    return result;
}

double Power(double base,int exponent){
    if(equal0(base) && exponent < 0){
        g_InvalidInput = true;
        return 0.0;
    }
    unsigned int absExponent = (unsigned int)(exponent);
    if(exponent < 0){
        absExponent = (unsigned int)(-exponent);
    }
    double result = PowerWithUnsignedExponent(base,absExponent);
    if(exponent < 0){
        result = 1.0 / result;
    }
    return result;
}


int main(){
    cout<<Power(2,9)<<endl;

}

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11861147.html