Skip to content

Commit e896533

Browse files
authored
Merge pull request #1164 from 0xff-dev/69
Add solution and test-cases for problem 69
2 parents 946ba88 + 826f64b commit e896533

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
package Solution
22

3+
import "sort"
4+
35
func mySqrt(x int) int {
46
r := x
57
for r*r > x {
68
r = (r + x/r) / 2
79
}
810
return r
911
}
12+
13+
func mySqrt1(x int) int {
14+
idx := sort.Search(x, func(i int) bool {
15+
return i*i >= x
16+
})
17+
if idx*idx == x {
18+
return idx
19+
}
20+
return idx - 1
21+
}

leetcode/1-100/0069.Sqrt-x/Solution_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,26 @@ func TestSolution(t *testing.T) {
2727
})
2828
}
2929
}
30+
31+
func TestSolution1(t *testing.T) {
32+
// 测试用例
33+
cases := []struct {
34+
name string
35+
inputs int
36+
expect int
37+
}{
38+
{"1 test 1", 4, 2},
39+
{"2 test 2", 8, 2},
40+
}
41+
42+
// 开始测试
43+
for _, c := range cases {
44+
t.Run(c.name, func(t *testing.T) {
45+
ret := mySqrt1(c.inputs)
46+
if !reflect.DeepEqual(ret, c.expect) {
47+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
48+
c.expect, ret, c.inputs)
49+
}
50+
})
51+
}
52+
}

0 commit comments

Comments
 (0)