解决方法:
加一个num=1 的判断条件即可
因为下标从 0 开始,当num=1 时,left 、right 、mid 的下标都是0,这样mid*mid = 0,所以 X =1 时要单独考虑
class Solution { public boolean isPerfectSquare(int num) { long left = 0, right = num - 1; //官方题解 //int left = 0, right = num - 1; if (num == 1) { return true; } while (left <= right){ long mid = (left + right) / 2; //int mid = (left + right) / 2; //long square = (long) mid * mid; (可以前面left、right、mid都用int,最后只在这一步进行强转) long sqrt = mid * mid; if (sqrt < num){ left = mid + 1; }else if (sqrt > num) { right = mid - 1; }else { return true; } } return false; } }
标签:平方,right,num,int,mid,return,L5,367,left From: https://www.cnblogs.com/18191xq/p/17815130.html