Skip to content

Commit 7b96e63

Browse files
author
applewjg
committed
Sqrt
Change-Id: I1fcca7720537bd8777b820629991c01ee03d4f98
1 parent a3b9763 commit 7b96e63

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Sqrt(x).java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
Author: King, [email protected]
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+
}

0 commit comments

Comments
 (0)