LeetCode 第 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
这道题可以借用第 69 题的代码。第 69 题中我们实现了自己的 Sqrt 函数,既然这道题不让用库函数中的 sqrt,那么我们就自己写个,用简单的二分查找法就可以。代码的具体解释见第 69 题的解答。
下面是代码。
int mySqrt(int x)
{
if(x <= 0) return 0;
int a1 = 1;
int a2 = 46341 * 2 - 1;
unsigned int a, y;
if(a2 > x / 2) a2 = x;
do
{
a = (a1 + a2) / 2;
y = a * a;
if(y == x) return a;
if(y > x)
{
a2 = a;
}
else
{
a1 = a;
}
}while(a1 + 1 < a2);
a = (a1 + a2) / 2;
return a;
}
bool isPerfectSquare(int num)
{
int z = mySqrt(num);
return z * z == num;
}
时间: 2024-11-05 20:37:53