Skip to content

Commit 42df1fe

Browse files
aQuaaQua
aQua
authored and
aQua
committed
69 accepted, 6ms. The fastest is 3ms.
1 parent abb211d commit 42df1fe

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

Algorithms/0069.sqrtx/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/)
2+
3+
## 题目
4+
Implement int sqrt(int x).
5+
6+
Compute and return the square root of x.
7+
8+
## 解题思路
9+
10+
见程序注释

Algorithms/0069.sqrtx/sqrtx.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package Problem0069
2+
3+
func mySqrt(x int) int {
4+
res := 1
5+
for !(res*res <= x && x < (res+1)*(res+1)) {
6+
res = (res + x/res) / 2
7+
}
8+
9+
return res
10+
}

Algorithms/0069.sqrtx/sqrtx_test.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package Problem0069
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
x int
18+
}
19+
20+
// ans 是答案
21+
type ans struct {
22+
one int
23+
}
24+
25+
func Test_Problem0069(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
15,
33+
},
34+
ans{
35+
3,
36+
},
37+
},
38+
39+
question{
40+
para{
41+
3,
42+
},
43+
ans{
44+
1,
45+
},
46+
},
47+
48+
question{
49+
para{
50+
9,
51+
},
52+
ans{
53+
3,
54+
},
55+
},
56+
57+
// 如需多个测试,可以复制上方元素。
58+
}
59+
60+
for _, q := range qs {
61+
a, p := q.ans, q.para
62+
fmt.Printf("~~%v~~\n", p)
63+
64+
ast.Equal(a.one, mySqrt(p.x), "输入:%v", p)
65+
}
66+
}

0 commit comments

Comments
 (0)