【leetcode刷题笔记】Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.


题解:二分的方法,从0,1,2.....x搜索sqrt(x)的值。

代码如下:

 1 public class Solution {
 2     public int sqrt(int x) {
 3         long l = 0;
 4         long r = x;
 5         
 6         while(l <= r){
 7             long mid = l + (r-l)/2;
 8             if(x == mid*mid)
 9                 return (int)mid;
10             else if(x < mid*mid)
11                 r = mid-1;
12             else {
13                 l = mid+1;
14             }
15         }
16         return (int)r;
17     }
18 }

需要注意的一点就是mid*mid的值有可能超过int的范围,所以要用long型规定各个变量。开始用的int型,结果出现了TLE的错误,猜想是int越界以后变成负数,就一直找不到sqrt(x)的值。

原文地址:https://www.cnblogs.com/sunshineatnoon/p/3853726.html