标签: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
}
};标签:c++ leetcode binary search array
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43637953