File tree Expand file tree Collapse file tree 3 files changed +122
-0
lines changed
Algorithms/0367. Valid Perfect Square Expand file tree Collapse file tree 3 files changed +122
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode
2+
3+ func isPerfectSquare (num int ) bool {
4+ low , high := 1 , num
5+ for low <= high {
6+ mid := low + (high - low )>> 1
7+ if mid * mid == num {
8+ return true
9+ } else if mid * mid < num {
10+ low = mid + 1
11+ } else {
12+ high = mid - 1
13+ }
14+ }
15+ return false
16+ }
Original file line number Diff line number Diff line change 1+ package leetcode
2+
3+ import (
4+ "fmt"
5+ "testing"
6+ )
7+
8+ type question367 struct {
9+ para367
10+ ans367
11+ }
12+
13+ // para 是参数
14+ // one 代表第一个参数
15+ type para367 struct {
16+ one int
17+ }
18+
19+ // ans 是答案
20+ // one 代表第一个答案
21+ type ans367 struct {
22+ one bool
23+ }
24+
25+ func Test_Problem367 (t * testing.T ) {
26+
27+ qs := []question367 {
28+
29+ question367 {
30+ para367 {1 },
31+ ans367 {true },
32+ },
33+
34+ question367 {
35+ para367 {2 },
36+ ans367 {false },
37+ },
38+
39+ question367 {
40+ para367 {3 },
41+ ans367 {false },
42+ },
43+
44+ question367 {
45+ para367 {4 },
46+ ans367 {true },
47+ },
48+
49+ question367 {
50+ para367 {5 },
51+ ans367 {false },
52+ },
53+
54+ question367 {
55+ para367 {6 },
56+ ans367 {false },
57+ },
58+
59+ question367 {
60+ para367 {104976 },
61+ ans367 {true },
62+ },
63+ // 如需多个测试,可以复制上方元素。
64+ }
65+
66+ fmt .Printf ("------------------------Leetcode Problem 367------------------------\n " )
67+
68+ for _ , q := range qs {
69+ _ , p := q .ans367 , q .para367
70+ fmt .Printf ("【input】:%v 【output】:%v\n " , p , isPerfectSquare (p .one ))
71+ }
72+ fmt .Printf ("\n \n \n " )
73+ }
Original file line number Diff line number Diff line change 1+ # [ 367. Valid Perfect Square] ( https://leetcode.com/problems/valid-perfect-square/ )
2+
3+ ## 题目:
4+
5+ Given a positive integer num, write a function which returns True if num is a perfect square else False.
6+
7+ ** Note:** ** Do not** use any built-in library function such as ` sqrt ` .
8+
9+ ** Example 1:**
10+
11+ Input: 16
12+ Output: true
13+
14+ ** Example 2:**
15+
16+ Input: 14
17+ Output: false
18+
19+
20+ ## 题目大意
21+
22+ 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
23+
24+ 说明:不要使用任何内置的库函数,如 sqrt。
25+
26+
27+
28+
29+ ## 解题思路
30+
31+
32+ - 给出一个数,要求判断这个数是不是完全平方数。
33+ - 可以用二分搜索来解答这道题。判断完全平方数,根据它的定义来,是否能被开根号,即找到一个数的平方是否可以等于待判断的数字。从 [ 1, n] 区间内进行二分,若能找到则返回 true,找不到就返回 false 。
You can’t perform that action at this time.
0 commit comments