码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 367. Valid Perfect Square

时间:2016-08-05 23:03:49      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Leetcode 367. Valid Perfect Square

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5742851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!