367. Valid Perfect Square

原题:

367. Valid Perfect Square

读题:

求一个整数是否为完全平方数,如1,4,9,16,……就是完全平方数,这题主要是运算效率问题

求解方法1:812ms

class Solution {
public:
bool isPerfectSquare(int num)
{
if(num < 0) return false;
int i = 0;
//这里要加1,不然num = 1时会出错
for(;i< num/2 + 1;i++)
{
if(i*i == num)
{
return true;
}
}
return false;
}
};

论坛高效率求解法:

class Solution {
public:
bool isPerfectSquare(int num) {
long left = 1, right = num;
while(left <= right){
long mid = left + (right - left) / 2;
long t = mid * mid;
if(t > num){
right = mid - 1;
}else if(t < num){
left = mid + 1;
}else
return true;
}
return false;
}
};

  

上一篇:sql 表中列值转成字符串


下一篇:unblock with 'mysqladmin flush-hosts'"