69. Sqrt(x) (MATH)

A little trick is using i <= x / i for comparison, instead of i * i <= x, to avoid exceeding integer upper limit.

 

二分法查找比较快

 

 1 class Solution {
 2     public int mySqrt(int x) {
 3         if(x == 0) return 0;
 4         if(x == 1) return 1;
 5         int left = 1, right = x / 2;
 6         while(left <= right) {
 7             int mid = left + (right - left) / 2;
 8             if(mid > x / mid) {
 9                 right = mid - 1;
10             }else if(mid == x / mid) {
11                 return mid;
12             }else {
13                 left = mid + 1;
14             }
15         }
16         return right;
17         
18     }
19 }

 

posted @ 2018-08-27 04:34  jasoncool1  阅读(129)  评论(0编辑  收藏  举报