剑指offer之面试题11数值的整数次方

问题描述

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

实现代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include<math.h>

double doDoublePower(double doubleNumber,int pow);
double doublePow(double doubleNumber,int pow);
int main(int argc, char *argv[])
{
	srand( (unsigned)time( NULL ) );
	int number = rand()%30;
	double d = 1.0/number;
	int pow = rand()%10;
	printf("double number is %lf, pow  is %d.\n",d,pow);
	double result = doublePow(d,pow);
	printf("this is result :%0.10lf\n",result);
	return 0;
}

double doublePow(double doubleNumber,int pow){
	if(pow==0){
		return 1.0;
	}else if(pow == 1 ){
		return doubleNumber;
	}
	bool isPositive = pow>0?true:false;
	if((doubleNumber-0.0)<1e-10 && !isPositive){
		printf("this is illegal\n");
		return 0.0;
	}
	if(!isPositive){
		printf("this is negative\n");
		pow=-pow;
	}
	double result = doDoublePower(doubleNumber,pow);
	if(!isPositive){
		result = 1.0/result;
	}
	return result;
}

double doDoublePower(double doubleNumber,int pow){
	if(pow==0){
		return 1.0;
	}else if(pow==1){
		return doubleNumber;
	}
	double doubleTemp= doDoublePower(doubleNumber,pow>>1);
	if(pow&0x1 == 1){
		return doubleNumber * doubleTemp*doubleTemp;
	}
	return doubleTemp*doubleTemp;
}

上面算法的时间复杂度是:O(lgn)。(n表示n次方)

参考资料
剑指offer

备注
转载请注明出处:http://blog.csdn.net/wsyw126/article/details/51367401
作者:WSYW126

你可能感兴趣的:(剑指offer)