标签:
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