Leetcode 367. Valid Perfect Square

367. Valid Perfect Square

  • Total Accepted: 11219
  • Total Submissions: 30842
  • Difficulty: Medium

 

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 class Solution {
 2 public:
 3     bool isPerfectSquare(int num) {
 4         int left=1,right=num-1;
 5         while(left<=right){
 6             long long mid=left+(right-left)/2;
 7             if(mid*mid<num){
 8                 left=mid+1;
 9             }
10             else{
11                 right=mid-1;
12             }
13         }
14         return left*left==num;
15     }
16 };

 

posted @ 2016-08-05 21:52  Deribs4  阅读(141)  评论(0编辑  收藏  举报