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

判断一个数是不是某个整数的平方

C++(0ms):

 1 class Solution {
 2 public:
 3     bool isPerfectSquare(int num) {
 4         int i = 1;
 5         while(num > 0){
 6             num -= i ;
 7             i += 2 ;
 8         }
 9         return num==0 ;
10     }
11 };

 

java(0ms):

 1 class Solution {
 2     public boolean isPerfectSquare(int num) {
 3         long low = 1 ;
 4         long high = num ;
 5         while(low <= high){
 6             long mid = (low + high)>>1 ;
 7             if (mid * mid == num){
 8                 return true ;
 9             }else if (mid * mid > num){
10                 high = mid-1 ;
11             }else{
12                 low = mid+1 ;
13             }
14         }
15         return false ;
16     }
17 }

 

posted @ 2017-11-19 22:10  __Meng  阅读(168)  评论(0编辑  收藏  举报