【Leetcode】Sqrt(x)

来源:互联网 发布:水果蔬菜批发软件 编辑:程序博客网 时间:2024/06/07 07:27

题目链接: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;  }  


0 0
原创粉丝点击