-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathisPerfectSquare.h
More file actions
49 lines (40 loc) · 1.08 KB
/
isPerfectSquare.h
File metadata and controls
49 lines (40 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// isPerfectSquare.h
// bsearch
//
// Created by junl on 2019/7/19.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef isPerfectSquare_hpp
#define isPerfectSquare_hpp
#include <stdio.h>
/*
367.给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-perfect-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
bool isPerfectSquare(int num) {
if (num<=1) return true;
int left=1;
int right=num/2;
while (left<right) {
int mid = left + (right-left)/2;
if (mid>=num/mid) {
//至少mid^2大于num
right=mid;
} else {
//mid^2无限逼近num
left=mid+1;
}
}
return (long)left*left == num;
}
#endif /* isPerfectSquare_hpp */