码迷,mamicode.com
首页 > 其他好文 > 详细

Sqrt(x) --LeetCode

时间:2015-04-08 10:57:54      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

实现sqrt(x)

思路:一般都是使用二分法,但是也可以使用牛顿法来实现更高的速度

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int Sqrt(int num)
{
	if(num == 1 && num == 0)
		return num;
	int low =1,high = num/2+1;
	int mid;
	while(low <= high)
	{
		mid = (high+low)/2;
		if(mid*mid<=num && (mid+1)*(mid+1)>num)
			return mid;
		if(mid*mid < num)
			low =mid+1;
		else
			high = mid-1;
	}
	return 0;
}

double SqrtSecond(double num)
{
	const double eps = 0.000001;
	double low = 0;
	double high = num;
	double mid;
	while((high-low)>eps)
	{
		mid = (low+high)/2;
		
		if(mid*mid== num)
			return mid;
		if(mid*mid > num)
			high = mid;
		else
			low = mid;
	}
	return mid;
}

int main() 
{
	cout<<SqrtSecond(2)<<endl;
	cout<<sizeof(float)<<" "<<sizeof(double)<<endl;
	return 0;
}


Sqrt(x) --LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44937311

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!