Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note:do no built-in library function such as sqrt
.
Example 1:
Input:16returns:true
Example 2:
Input:14returns:false
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Solution One:
1 Public classSolution {2 Public BooleanIsperfectsquare (intnum) {3 if(Num < 0)return false;4 if(num = = 1)return true;5 for(inti = 1; i<= num/i;i++){6 if(i*i = = num)return true;7 }8 return false;9 }Ten}
Solution 2: Binary Lookup method (Java without AC for reference only)
1 Public classSolution {2 Public BooleanIsperfectsquare (intnum) {3 if(Num < 0)return false;4 if(num = = 1)return true;5 intLow = 0, high = NUM/2;6 while(Low <=High ) {7 LongMid = (low + high)/2;8 LongTMP = mid*mid;9 if(tmp = = num)return true;Ten if(tmp > num) high = Mid-1; One ElseLow = mid + 1; A } - return false; - } the}
The solution 3:https://leetcode.com/discuss/110659/o-1-time-c-solution-inspired-by-q_rsqrt the O (1) Solution of the Great God.
Solution 4:
The total number of squares is a series of odd sum, for example:
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
1 Public classSolution {2 Public BooleanIsperfectsquare (intnum) {3 inti = 1;4 while(num > 0) {5num-=i;6i + = 2;7 }8 returnnum = = 0;9 }Ten}
367. Valid Perfect Square Java Solutions