Implement int sqrt(int x).

Compute and return the square root of x.

Hide Tags

Math Binary Search

 
 

    并未使用牛顿迭代,实现是通过二分搜索实现的,需要注意判断时候 x* x<K 容易溢出,所以可以改为  x< k/x。
 
#include <iostream>
using namespace std; class Solution {
public:
int sqrt(int x) {
if(x <) return x;
int lft = ,rgt = x;
int mid = (lft+rgt)/;
while(lft+<rgt){
if(mid == x/mid) return mid;
if(mid < x/ mid){
lft = mid;
}
else{
rgt = mid;
}
mid = (lft+rgt)/;
}
if( rgt<=mid/rgt) return rgt;
return lft;
}
}; int main()
{
Solution sol;
for(int i =;i<;i++)
cout<<sol.sqrt(i)<<endl;
return ;
}
05-14 02:32