leetcode367- Valid Perfect Square- easy
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
算法:1.二分法O(logN)。用mid*mid与num比较。细节是看到这种乘法在中间的都要小心溢出,mid用long格式!!不然如果mid比较大100000乘一下溢出变成负数那你就不能得到正确的比较结果了。
2.数学法(O(sqrtN))。因为所有的完美平方数都是1+3+5+...得到的,那你就可以这样加下去到逼近它。
1.二分法(O(logN))
class Solution { public boolean isPerfectSquare(int num) { if (num < 0) { return false; } long start = 1; long end = num; while (start + 1 < end) { long mid = start + (end - start) / 2; if (mid * mid < num) { start = (int) mid; } else { end = (int) mid; } } if (start * start == num || end * end == num) { return true; } return false; } }
2.O(sqrtN)
class Solution { public boolean isPerfectSquare(int num) { int sum = 0; int digit = 1; while (sum < num) { sum += digit; digit += 2; } if (sum == num) { return true; } return false; } }