问题链接:https://leetcode.com/problems/valid-perfect-square/
原文:http://www.cnblogs.com/guoguolan/p/5619443.html
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 public class Solution { 2 public boolean isPerfectSquare(int num) { 3 if(num < 0) return false; 4 if(num == 1) return true; 5 for(int i = 1; i<= num/i;i++){ 6 if(i*i == num) return true; 7 } 8 return false; 9 } 10 }
解法2: 二分查找法 (java 没有ac 仅供参考)
1 public class Solution { 2 public boolean isPerfectSquare(int num) { 3 if(num < 0) return false; 4 if(num == 1) return true; 5 int low = 0, high = num/2; 6 while(low <= high){ 7 long mid = (low + high)/2; 8 long tmp = mid*mid; 9 if(tmp == num) return true; 10 if(tmp > num) high = mid - 1; 11 else low = mid + 1; 12 } 13 return false; 14 } 15 }
解法3:https://leetcode.com/discuss/110659/o-1-time-c-solution-inspired-by-q_rsqrt 大神的 O(1) 解法。
class Solution {
public:
bool isPerfectSquare(int num) {
if (num < 0) return false;
int root = floorSqrt(num);
return root * root == num;
}
int32_t floorSqrt(int32_t x) {
double y=x; int64_t i=0x5fe6eb50c7b537a9;
y = *(double*)&(i = i-(*(int64_t*)&y)/2);
y = y * (3 - x * y * y) * 0.5;
y = y * (3 - x * y * y) * 0.5;
i = x * y + 1; return i - (i * i > x);
}
};
解法4:
完全平方数是一系列奇数之和,例如:
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
1 public class Solution { 2 public boolean isPerfectSquare(int num) { 3 int i = 1; 4 while (num > 0) { 5 num -= i; 6 i += 2; 7 } 8 return num == 0; 9 } 10 }