# [LeetCode] 367. Valid Perfect Square 检验完全平方数

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True


Example 2:

Input: 14
Returns: False


Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

class Solution {
public:
bool isPerfectSquare(int num) {
if (num == 1) return true;
long x = num / 2, t = x * x;
while (t > num) {
x /= 2;
t = x * x;
}
for (int i = x; i <= 2 * x; ++i) {
if (i * i == num) return true;
}
return false;
}
}; 

class Solution {
public:
bool isPerfectSquare(int num) {
for (int i = 1; i <= num / i; ++i) {
if (i * i == num) return true;
}
return false;
}
}; 

class Solution {
public:
bool isPerfectSquare(int num) {
long left = 0, right = num;
while (left <= right) {
long mid = left + (right - left) / 2, t = mid * mid;
if (t == num) return true;
if (t < num) left = mid + 1;
else right = mid - 1;
}
return false;
}
};

1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+(2n-1) = (2n-1 + 1)n/2 = n*n

class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
};

class Solution {
public:
bool isPerfectSquare(int num) {
long x = num;
while (x * x > num) {
x = (x + num / x) / 2;
}
return x * x == num;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/367

Sqrt(x)

https://leetcode.com/problems/valid-perfect-square/

https://leetcode.com/problems/valid-perfect-square/discuss/83872/O(1)-time-c%2B%2B-solution-inspired-by-Q_rsqrt

https://leetcode.com/problems/valid-perfect-square/discuss/83874/A-square-number-is-1%2B3%2B5%2B7%2B...-JAVA-code

https://leetcode.com/problems/valid-perfect-square/discuss/83902/Java-Three-Solutions-135..-SequenceBinary-SearchNewton

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2016-06-27 09:53  Grandyang  阅读(15301)  评论(7编辑  收藏  举报