use double to avoid overflow


  • 0

    Re: [A square number is 1+3+5+7+...](JAVA code)
    use double to avoid overflow

        public boolean isPerfectSquare(int num) {
            int left = 1, right = num;
            while (left < right) {
                int mid = left + (right - left) / 2;
                double res = num / 1.0 / mid;
                if (res == mid) 
                    return true;
                else if (res > mid) 
                    left = mid + 1;
                else 
                    right = mid;
            }
            return left * left == num;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.