首页 > 其他 > 详细

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

时间:2019-11-14 20:06:44      阅读:139      评论:0      收藏:0      [点我收藏+]
/*
题目:
	实现函数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;

}

   

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

原文:https://www.cnblogs.com/buaaZhhx/p/11861147.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!