LeetCode:Valid Perfect Square

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

思路:这里使用二分法来进行查找,注意如果直接使用乘法会溢出,因此这里使用了除法。

 1     bool isPerfectSquare(int num) {
 2         if (num == 1)
 3             return 1;
 4         int b = 0;
 5         int e = num / 2;
 6         while (b <= e)
 7         {
 8             int m = (b + e) / 2;
 9             if (num%m==0&&num/m ==m)
10                 return true;
11             else if (m >= num/m)
12                 e = m - 1;
13             else
14                 b = m + 1;
15         }
16         return false;
17     }

 

如果你有任何疑问或新的思路,欢迎在下方评论。

posted @ 2017-04-12 13:44  陆小风不写代码  阅读(136)  评论(0编辑  收藏  举报