-
Notifications
You must be signed in to change notification settings - Fork 0
/
367.有效的完全平方数.js
48 lines (41 loc) · 947 Bytes
/
367.有效的完全平方数.js
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
/*
* @lc app=leetcode.cn id=367 lang=javascript
*
* [367] 有效的完全平方数
*/
// @lc code=start
/**
* @param {number} num
* @return {boolean}
*/
var isPerfectSquare = function (num) {
/**
* 二分查找法
*/
// if (num < 2) return true;
// let left = 2,
// right = ~~(num / 2),
// guessSquared;
// while(left + 1 < right) {
// let mid = left + ~~((right -left) / 2);
// guessSquared = mid * mid;
// if (guessSquared === num) {
// return true;
// } else if (guessSquared > num) {
// right = mid;
// } else {
// left = mid;
// }
// }
// return right * right === num || left * left === num;
/**
* 牛顿迭代法
*/
if (num < 2) return true;
let x = num / 2;
while (x * x > num) {
x = (x + num / x) / 2 | 0;
}
return num === x * x;
};
// @lc code=end