File tree Expand file tree Collapse file tree 2 files changed +33
-39
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +33
-39
lines changed Original file line number Diff line number Diff line change 2
2
3
3
/**
4
4
* 69. Sqrt(x)
5
+ *
5
6
* Implement int sqrt(int x).
6
7
* Compute and return the square root of x.
7
8
*/
8
9
9
10
public class _69 {
10
- public int mySqrt (int x ) {
11
- long left = 0 ;
12
- long right = x / 2 + 1 ;
13
- while (left <= right ) {
14
- long mid = left + (right - left ) / 2 ;
15
- long result = mid * mid ;
16
- if (result == (long ) x ) {
17
- return (int ) mid ;
18
- } else if (result > x ) {
19
- right = mid - 1 ;
20
- } else {
21
- left = mid + 1 ;
11
+ public static class Solution1 {
12
+ /**A few key points:
13
+ * 1. all variable use long type, otherwise overflow, just cast to int before returning
14
+ * 2. left start from 0, not 1
15
+ * 3. right start from x/2 + 1, not from x*/
16
+ public int mySqrt (int x ) {
17
+ long left = 0 ;
18
+ long right = x / 2 + 1 ;
19
+ while (left <= right ) {
20
+ long mid = left + (right - left ) / 2 ;
21
+ long result = mid * mid ;
22
+ if (result == (long ) x ) {
23
+ return (int ) mid ;
24
+ } else if (result > x ) {
25
+ right = mid - 1 ;
26
+ } else {
27
+ left = mid + 1 ;
28
+ }
22
29
}
30
+ return (int ) right ;
23
31
}
24
- return (int ) right ;
25
32
}
26
33
}
Original file line number Diff line number Diff line change 1
1
package com .fishercoder ;
2
2
3
3
import com .fishercoder .solutions ._69 ;
4
- import org .junit .Before ;
5
4
import org .junit .BeforeClass ;
6
5
import org .junit .Test ;
7
6
8
7
import static junit .framework .Assert .assertEquals ;
9
8
10
- /**
11
- * Created by fishercoder on 1/25/17.
12
- */
13
9
public class _69Test {
14
- private static _69 test ;
15
- private static int expected ;
16
- private static int actual ;
17
- private static int input ;
10
+ private static _69 .Solution1 solution1 ;
18
11
19
- @ BeforeClass
20
- public static void setup () {
21
- test = new _69 ();
22
- }
12
+ @ BeforeClass
13
+ public static void setup () {
14
+ solution1 = new _69 . Solution1 ();
15
+ }
23
16
24
- @ Before
25
- public void setupForEachTest () {
26
- expected = 0 ;
27
- actual = 0 ;
28
- input = 0 ;
29
- }
17
+ @ Test
18
+ public void test1 () {
19
+ assertEquals (4 , solution1 .mySqrt (16 ));
20
+ }
30
21
31
- @ Test
32
- public void test1 () {
33
- expected = 4 ;
34
- input = 16 ;
35
- actual = test .mySqrt (input );
36
- assertEquals (expected , actual );
37
-
38
- }
22
+ @ Test
23
+ public void test2 () {
24
+ assertEquals (2 , solution1 .mySqrt (8 ));
25
+ }
39
26
}
You can’t perform that action at this time.
0 commit comments