Valid Perfect Square

LeetCode Q 367 - Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Solution

Code:

public boolean isPerfectSquare(int num) {
	int left = 1, right = Integer.MAX_VALUE;
	while (true) {
		int mid = left + (right - left) / 2;
		if (num % mid == 0 && mid == num / mid)
			return true;
		else if (mid > num / mid)
			right = mid - 1;
		else {
			if (mid + 1 > num / (mid + 1))
				return false;
			left = mid + 1;
		}
	}
}

   Reprint policy


《Valid Perfect Square》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC