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

leetcode_69_Sqrt(x)

时间:2015-02-08 16:55:02      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   binary search   array   

欢迎转载,如有错误或疑问请留言纠正,谢谢技术分享


Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.


//vs2012测试代码
//using binary search to solve sqrt(x)
//alternative method: newton method

#include<iostream>

using namespace std;

class Solution {
public:
    int sqrt(int x) 
	{
       if(x==0 || x==1)
		   return x;
	   int left = 1, right=x;
	   while( left<=right )
	   {
		   int mid = left + (right-left)/2;
		   long long mult = (long long)mid*mid;  //这里如果mid*mid前面不强制转换为(long long)会溢出
		   if( mult == x)
			   return mid;
		   else if ( mult < x )
			   left = mid+1;
		   else if ( mult > x )
			   right = mid-1;
		   
	   }
	   return right; //the small one is the answer
    }
};

int main()
{
	int x;
	cin>>x;
	Solution lin;
	cout<<lin.sqrt(x)<<endl;
	return 0;
}



//方法一:自测Accepted
//using binary search to solve sqrt(x)
//alternative method: newton method
class Solution {
public:
    int sqrt(int x) 
	{
       if(x==0 || x==1)
		   return x;
	   int left = 1, right=x;
	   while( left<=right )
	   {
		   int mid = left + (right-left)/2;
		   long long mult = (long long)mid*mid;  //这里如果mid*mid前面不强制转换为(long long)会溢出
		   if( mult == x)
			   return mid;
		   else if ( mult < x )
			   left = mid+1;
		   else if ( mult > x )
			   right = mid-1;
		   
	   }
	   return right; //the small one is the answer
    }
};



//方法二:其他人版本
class Solution {
//using binary search to solve sqrt(x)
//alternative method: newton method
public:
	int sqrt(int x) {
		if(x <= 1) return x;
		int l = 0; 
		int r = x;
		while (l <= r)
		{
			int m = l+(r-l)/2;
			int now = x/m;//avoid overflow
			if (now < m)
				r = m-1;
			else if(now > m)
				l = m+1;
			else return m;
		}
		return r;//the small one is the answer
	}
};


leetcode_69_Sqrt(x)

标签:c++   leetcode   binary search   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43637953

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