标签:
题目链接:https://leetcode.com/problems/sqrtx/
题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:
二分法搜索平方数 要注意,如果不能完整的开方,要取靠左边的数,
算法:
public int mySqrt(int x) { int left = 1,right = x,mid =0; int last_mid = mid; while(left<=right){ mid = left+(right-left)/2; if(mid>x/mid){ right = mid-1; }else if(mid<x/mid){ left = mid+1; last_mid = mid; }else{ return mid; } } return last_mid; }
标签:
原文地址:http://blog.csdn.net/yeqiuzs/article/details/51493601