50 - Pow(x, n)

用二分法,O(logn)。注意n < 0的处理

/*
*/

#include "stdafx.h"
#include <iostream>

using namespace std;

class Solution_050_PowXn
{
public:
	double power(double x, int n)
	{
		if (n == 0)
		{
			return 1;
		}

		double v = power(x, n / 2);

		if (n % 2 == 0)
		{
			return v * v;
		}
		else
			return v * v * x;
	}


	double myPow(double x, int n)
	{
		if (n < 0)
			return 1.0 / power(x, -n);
		else
			return power(x, n);
	}
};


你可能感兴趣的:(50 - Pow(x, n))