程序员面试100题之四十四,数值的整数次方

#include "stdafx.h"

#include <bitset>



double Power(double base, int exp)

{

	std::bitset<32> bits(exp);

	int numOf1 = bits.count();

	double tempResult[32];

	for(int i=0;i<32;i++)

		tempResult[i] = 1.0;



	int count=0;

	double power = 1.0;

	for(int i=0;i<32&&count<numOf1;i++)

	{

		if(i==0)

			power = base;

		else

			power = power * power;

		if(bits.at(i))

		{

			tempResult[i] = power;

			++count;

		}

	}

	power = 1.0;

	for(int i=0;i<32;i++)

	{

		if(bits.at(i))

			power *= tempResult[i];

	}

	return power;



}



int _tmain(int argc, _TCHAR* argv[])

{

	printf("%lf\n",Power(2.5,2));

	return 0;

}



你可能感兴趣的:(程序员)