原题:
读题:
求一个整数是否为完全平方数,如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; } };