File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Date: Apr 18, 2013
4
+ Problem: Sqrt(x)
5
+ Difficulty: Easy
6
+ Source: http://leetcode.com/onlinejudge#question_69
7
+ Notes:
8
+ Implement int sqrt(int x).
9
+ Compute and return the square root of x.
10
+
11
+ Solution: 1. Binary search in range [0, x / 2 + 1].
12
+ 2. Newton iteration method. x(i+1) = (x(i) + n/x(i)) / 2.
13
+ See my blog (http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html) for more explanation (in Chinese).
14
+ */
15
+ public class Solution {
16
+ public int sqrt (int x ) {
17
+ int left = 1 , right = x /2 ;
18
+ if (x <2 ) return x ;
19
+ while (left <= right ) {
20
+ int mid = (left + right )/2 ;
21
+ if (x /mid == mid ) return mid ;
22
+ if (x /mid > mid ) left = mid + 1 ;
23
+ else right = mid - 1 ;
24
+ }
25
+ return right ;
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments