class Solution { public: bool isPerfectSquare(int num) { /* //方法一:蜜汁超时…… if (num < 0) return false; if (num == 1) return true; for (int i=1;i*i<=num;i++){ if (i*i==num) return true; } return false; }*/ /* //方法二:是对的! if(num < 0) return false; if(num == 1) return true; for(int i = 1; i<= num/i;i++){ if(i*i == num) return true; } return false; } */ //方法三:值得学习的【二分查找】 if (num < 0) return false; if (num == 1) return true; int left = 0; //注意! int right = num/2; //注意! long mid; long val; while (left <= right){ mid = (left + right)/2; val = mid * mid; if (val == num) return true; else if (val > num) right = mid - 1; else left = mid + 1; } return false; } };