Leetcode 69: Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.


Example 1:

Input: 4
Output: 2

 

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

 

 Note: BinarySearch is easy to understand but difficult to be bug free.

 1 public class Solution {
 2     public int MySqrt(int x) {
 3         if (x <= 1) return x;
 4         
 5         int low = 1, high = x;
 6         while (low < high)
 7         {
 8             int mid = low + (high - low) / 2;
 9             if (mid == x / mid)
10             {
11                 return mid;
12             }
13             else if (mid > x / mid)
14             {
15                 high = mid;
16             }
17             else
18             {
19                 low = mid + 1;
20             }
21         }
22         
23         return low - 1;
24     }
25 }

 

 

 
 
 
posted @ 2017-11-10 10:58  逸朵  阅读(117)  评论(0)    收藏  举报