首页 > 代码库 > LeetCode_49pow [Pow(x, n)]

LeetCode_49pow [Pow(x, n)]

#pragma warning(disable:4996)

#include <cstdio>
#include <tchar.h>
#include <Windows.h>

/*
	submit time : 3
		1.Runtime Error
			34.00515, -3
		2.Runtime Error
			1.00000, -2147483648
	request :
		Implement pow(x, n).
*/

double powRecursively(double x, int n) {
	if (n == 0) return 1;
	if (n == 1) return x;
	if (n == 2) return x*x;

	if (n & 0x1) {
		double temp = powRecursively(x, (n - 1) >> 1);
		return x * temp * temp;
	}
	else {
		double temp = powRecursively(x, n >> 1);
		return temp*temp;
	}
}

double pow(double x, int n) {
	if (n == -2147483647 - 1)
		return 1.0 / x * pow(x, n + 1);

	int sign = n < 0 ? -1 : 1;
	n = n < 0 ? -n : n;

	return sign == 1 ? powRecursively(x, n) : 1.0 / powRecursively(x, n);
}

//=================Test==================
void Test(double x, int n) {
	double result = pow(x, n);
	printf("pow(%lf, %d) is : %lf\n", x, n, result);
}

void Test1() {
	double x = 3.1415;
	Test(x, 5);
}

void Test2() {
	double x = 3.1415;
	Test(x, 50);
}

void Test3() {
	double x = 34.00515;
	Test(x, -3);
}

void Test4() {
	double x = 1.00000;
	Test(x, -2147483647-1);
}

int _tmain(int argc, _TCHAR* argv[]) {
	Test1();
	Test2();
	Test3();
	Test4();

	system("pause");
	return 0;
}