367. Valid Perfect Square java solutions

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.

 

Subscribe to see which companies asked this question

解法一:
 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)  解法。

 

解法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 }

 

posted @ 2016-06-27 10:32  Miller1991  阅读(827)  评论(0编辑  收藏  举报