首页 > 其他 > 详细

LeetCode_49pow [Pow(x, n)]

时间:2014-07-23 17:39:11      阅读:318      评论:0      收藏:0      [点我收藏+]
#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;
}



LeetCode_49pow [Pow(x, n)],布布扣,bubuko.com

LeetCode_49pow [Pow(x, n)]

原文:http://my.oschina.net/ITHaozi/blog/294142

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